Get every other value from a list in lodash

You can filter a list in lodash to get every other value. This is useful if, e.g. you are using solr, which returns facet results as a list of alternating facet name and the count (i.e. [“DropBox”, 100, “GoogleDocs”, 10, “OneDrive”, 0])

If you want the odd values:

_.filter(['a','b','c','d'], 
  (value, idx) => idx % 2 === 0
);

['a', 'c']

If you want the even values:

_.filter(['a','b','c','d'], 
  (value, idx) => idx % 2 === 1
);

['a', 'c']

As an alternate option, you can turn the list into lists of pairs, like so (you can turn this into a map with “fromPairs”).

Starting data:

["DropBox", 0, "GoogleDocs", 0, "OneDrive", 0]

Result:

[["Dropbox, 0], ["GoogleDocs", 0], ["OneDrive", 0]]
 _.values(
  _.groupBy(
    _.toPairs(values), 
      (v) => v[0] - v[0] % 2
    )
    .map( 
      (v) => [v[0][1], v[1][1]] 
);