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

前端 未结 3 1955
醉话见心
醉话见心 2020-12-14 19:45

Consider the following simple array:

var foods = [\'hotdog\', \'hamburger\', \'soup\', \'sandwich\', \'hotdog\', \'watermelon\', \'hotdog\'];
3条回答
  •  心在旅途
    2020-12-14 20:12

    var foods = ['hotdog', 'hamburger', 'soup', 'sandwich', 'hotdog', 'watermelon', 'hotdog'];
    var result = _.chain(foods).countBy().pairs().max(_.last).head().value();
    console.log(result);

    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.

提交回复
热议问题