Search code examples
javascriptlodash

How to get most repeated object property value using lodash?


I am new to lodash and was wondering how I could use it to get the most repeated property value in an object array. Like say I have an array such as

var arr1 = [{points: 50, player: LeBron James},{points: 32, player: Kevin Durant},{points: 62, player: LeBron James},{points: 90, player: LeBron James}]

In the player property in arr1, "LeBron James" is the most repeated. How would I get this using lodash? Thanks again.


Solution

  • Simply use _.uniqBy() It creates duplicate-free version of an array.

    var objects = [{points: 50, player: 'LeBron James'},{points: 32, player: 'Kevin Durant'},{points: 62, player: 'LeBron James'},{points: 90, player: 'LeBron James'}];
    
    var result = _.head(_(objects)
      .countBy('player')
      .entries()
      .maxBy(_.last));
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.min.js"></script>