Get the element with the highest occurrence in an array

后端 未结 30 1551
野性不改
野性不改 2020-11-22 11:17

I\'m looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

[\'pear\', \'a         


        
30条回答
  •  旧时难觅i
    2020-11-22 11:47

    const mode = (str) => {
      return str
        .split(' ')
        .reduce((data, key) => {
          let counter = data.map[key] + 1 || 1
          data.map[key] = counter
    
          if (counter > data.counter) {
            data.counter = counter
            data.mode = key
          }
    
          return data
        }, {
          counter: 0,
          mode: null,
          map: {}
        })
        .mode
    }
    
    console.log(mode('the t-rex is the greatest of them all'))
    

提交回复
热议问题