Getting the most commonly repeated object value from an array

It's pretty easy using lodash or underscore.js

TAGS: lodash,underscore,javascript

12/10/2015

I found a very useful answer from stack overflow with a concise method on how to find the most commonly repeating value in an array or object array using underscore or lodash.

For example, imagine you have an array of objects:


var objArray = [
  { id: 1, name: "name1", tag: "tag1" },
  { id: 2, name: "name2", tag: "tag1" },
  { id: 3, name: "name3", tag: "tag2" },
  { id: 4, name: "name4", tag: "tag1" },
  { id: 5, name: "name5", tag: "tag1" },
  { id: 6, name: "name6", tag: "tag2" }
];

and you want to find out which tag occurs the most frequently. You can simply use this method:


var tagArray = _.pluck(objArray,'tag'); //create an array of tag values from the object array
var mostCommonTag = _.chain(tagArray).countBy().pairs().max(_.last).head().value(); //find the most commonly occurring tag value

if you have an array of values rather than objects, you can obviously just remove the _.pluck and run the second line on your value array instead

The underscore/lodash methods used are:

pluck: Returns an array containing the tags from the object array
countBy: Sorts a list into groups and returns a count for the number of objects in each group.
pairs: Convert an object into a list of [key, value] pairs.
max: Returns the maximum value in list. If an iterator function is provided, it will be used on each value to generate the criterion by which the value is ranked.
last: Returns the last element of an array
head: Returns the first element of an array
chain: Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is used.
value: Extracts the value of a wrapped object.

Here's a demo: