-1

I am looking for a function (preferably using lodash, etc.) that will take the array and yield the expected output as follows:

const arr = [{name: 'Anna', score:4}, {name: 'Bob', score:5}, {name: 'Chris', score:4}]

// expected output
// [{name: 'Anna', score:4}, {name: 'Chris', score:4}, {name: 'Bob', score:5}]

i.e. the function should sort by:

1) the frequency of the 'score' property

2) the 'name' property (where scores are equal)

Note that because of (1), this question is not the same as those marked as duplicates.

Rich Ashworth
  • 1,995
  • 4
  • 19
  • 29
  • 1
    You probably would have gotten more traction with this if you had shown your own attempts at this. I don't think it was correct to close this based on the answers linked, because they aren't sorting by frequency. In any case, I'd suggest investigating the groupBy operator in lodash. You basically want to group by the score, and order by the length of the groups. – rfestag Sep 03 '18 at 19:55
  • I believe this is not a duplicate, as here we are looking to sort by value frequency, rather than by value – Rich Ashworth Sep 03 '18 at 19:55
  • `var _ = require('lodash'); const results = [{name: 'Anna', score:4}, {name: 'Bob', estimateValue:5},{name: 'Chris', estimateValue:4}]; const counts = _.countBy(results, x => x['score']); const r = results.map(x => ({...x, ...{'count': counts[x['score']]}})); _.orderBy(r, 'count')` works... – Rich Ashworth Sep 03 '18 at 19:57
  • 1
    The problem with countBy is you lose the context of the names (which you say you also want to order by in the end). If you use groupBy, you'll keep those names, and can map them to the correct order in the end. If you don't need to order by name, countBy will generally be better because it will require significantly less memory when operating on larger lists (you just keep the accumulation count instead of an array of all values) – rfestag Sep 03 '18 at 20:01
  • Thanks, it seems that in lodash it's possibly to pass an array into _`.orderBy`. So `_.orderBy(r, ['count', 'name']` should work. – Rich Ashworth Sep 03 '18 at 20:09

1 Answers1

0

You can use the sort function to sort on a specific key.

const arr = [{name: 'Anna', score:4}, {name: 'Bob', score:5}, {name: 'Chris', score:4}]

arr.sort((a,b) => {
   return a.score === b.score ? a.name > b.name :  a.score > b.score;
});

console.log(arr);
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44