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
)?
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.
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With