0

I have this array :

            array = [ 
        { id:1,
        name:"mike"},
        { id:6,
        name:"mike"},
        { id:2,
        name:"clay"},
        { id:3,
        name:"mike"},
        { id:4,
        name:"henry"},
        { id:5,
        name:"henry"},
    ]

I would like to sort it by frequency of the name and show only the top 2 entries

So at first I would get this array after sorting it and filtering the duplicates with reduce :

array2 = [ 
            {name:"mike"},
            {name:"henry"},
            {name:"clay"}
        ]

Then I would like to show only the top 2 entries of the array meaning this :

array3 = [ 
            {name:"mike"},
            {name:"henry"}
         ]
at out
  • 11
  • Well reduce makes sure the values of the array are filtered so it does the job of a sort and filter functions all in one – at out Jul 18 '22 at 09:45
  • Here is an example, I just don't know how to implement it in my case : https://stackoverflow.com/questions/50245957/sorting-array-with-javascript-reduce-function – at out Jul 18 '22 at 10:02

1 Answers1

0

Given the array:

array = [ 
        { id:1,
        name:"mike"},
        { id:6,
        name:"mike"},
        { id:2,
        name:"clay"},
        { id:3,
        name:"mike"},
        { id:4,
        name:"henry"},
        { id:5,
        name:"henry"},
    ]

Use the below compare function to sort the object array.

function compare( a, b ) {
  if ( a.name < b.name ){
    return -1;
  }
  if ( a.name > b.name ){
    return 1;
  }
  return 0;
}

 var sortedArray = array.sort( compare );

Then you can use the spread operator to sort the array.

 var distinctArray = [...new Set(sortedArray.map(x => x.name))];

Finally use splice to take first 2 items.

let finalArray = distinctArray.slice(0, 2);

Here is a working example.

Preetha Pinto
  • 274
  • 2
  • 8
  • I can do it using a sort function but I am trying to do it with a reduce. Do you know how to do it with reduce ? – at out Jul 17 '22 at 23:50
  • Why don't you want to use the sort function to sort? Any particular reason you want to use reduce? – Preetha Pinto Jul 18 '22 at 05:14
  • I am basing myself of this post : https://stackoverflow.com/questions/50245957/sorting-array-with-javascript-reduce-function – at out Jul 18 '22 at 09:46