Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js: Find the most frequently occurring value in an array?

Consider the following simple array:

var foods = ['hotdog', 'hamburger', 'soup', 'sandwich', 'hotdog', 'watermelon', 'hotdog'];

With underscore, is there a function or combination of functions I can use to select the most frequently occurring value (in this case it's hotdog)?

like image 492
k00k Avatar asked Sep 18 '13 17:09

k00k


People also ask

What is _ find in JavaScript?

The _. find() function looks at each element of the list and returns the first occurrence of the element that satisfy the condition. If any element of list is not satisfy the condition then it returns the undefined value.

Is underscore JS still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

Why underscore is used in JavaScript?

The Underscore. js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invokes, etc even without using any built-in objects. The _. first() function is used to return the first element of the array, i.e. the number at the zeroth index.


1 Answers

var foods = ['hotdog', 'hamburger', 'soup', 'sandwich', 'hotdog', 'watermelon', 'hotdog'];
var result = _.chain(foods).countBy().pairs().max(_.last).head().value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>

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.

like image 100
Bobby Avatar answered Nov 15 '22 13:11

Bobby