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]] 
);

Interested in JavaScript? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *