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

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

Consider the following simple array:

var foods = [\'hotdog\', \'hamburger\', \'soup\', \'sandwich\', \'hotdog\', \'watermelon\', \'hotdog\'];
3条回答
  •  失恋的感觉
    2020-12-14 20:03

    Based off previous answers, here's my version to calculate mode for either an array of strings or numbers that accounts for draws in mode (when values have equal frequency) and also returns the frequency. You can then choose what to do with them.

    Underscore and Lodash included.

    // returns
    // [['item', frequency]] where item is a string and frequency is an interger
    // [['item', frequency], ['item', frequency], ['item', frequency] ... ] for draws
    
    // examples:
    // unique mode: creed appears the most times in array
    // returns: [['creed', 4]]
    
    // draw mode: 'jim' and 'creed' both occur 4 times in array
    // returns: [['jim', 4], ['creed', 4]]
    
    // underscore:
    const usMode = arr => _.chain(arr).countBy().pairs().value().sort((a, b) => b[1] - a[1]).filter((e,i,a) => e[1] === a[0][1])
    
    // lodash
    const ldMode = arr => _.chain(arr).countBy().toPairs().value().sort((a, b) => b[1] - a[1]).filter((e,i,a) => e[1] === a[0][1])
    
    // usage
    usMode([1,2,3,3,3,4,5,6,7])
    // [['3', 3]]
    

    using underscore:

    // underscore
    
    const strsUniqueArr = ['jim','pam','creed','pam','jim','creed','creed','creed']
    const strsDrawArr = ['pam','jim','creed','jim','jim','creed','creed','creed', 'pam', 'jim']
    const numsUniqueArr = [1, 2, 2, 2, 2, 3 ,4, 5]
    const numsDrawArr = [1, 1, 1, 1, 2, 2, 2, 2, 3 ,4, 5]
    
    const usMode = arr =>  _.chain(arr).countBy().pairs().value().sort((a, b) => b[1] - a[1]).filter((e,i,a) => e[1] === a[0][1])
    
    console.log('empty', usMode([]))
    console.log('unique strs', usMode(strsUniqueArr))
    console.log('draw sts', usMode(strsDrawArr))
    console.log('unique nums', usMode(numsUniqueArr))
    console.log('draw nums', usMode(numsDrawArr))

    using lodash:

    // lodash
    
    const strsUniqueArr = ['jim','pam','creed','pam','jim','creed','creed','creed']
    const strsDrawArr = ['pam','jim','creed','jim','jim','creed','creed','creed', 'pam', 'jim']
    const numsUniqueArr = [1, 2, 2, 2, 2, 3 ,4, 5]
    const numsDrawArr = [1, 1, 1, 1, 2, 2, 2, 2, 3 ,4, 5]
    
    const ldMode = arr =>  _.chain(arr).countBy().toPairs().value().sort((a, b) => b[1] - a[1]).filter((e,i,a) => e[1] === a[0][1])
    
    console.log('empty', ldMode([]))
    console.log('unique strs', ldMode(strsUniqueArr))
    console.log('draw sts', ldMode(strsDrawArr))
    console.log('unique nums', ldMode(numsUniqueArr))
    console.log('draw nums', ldMode(numsDrawArr))

提交回复
热议问题