Filter and sort a JavaScript array
array.sort((a, b) => {
if(a.number === b.number) {
// If two elements have same number, then the one who has larger rating.average wins
return b.rating.average - a.rating.average;
} else {
// If two elements have different number, then the one who has larger number wins
return b.number - a.number;
}
});
array = array.filter((element, index) => {
return index === 0 || element.number !== array[index-1].number;
});
For your test case,
[{
"number": "4",
"fileName": "fileXX",
"rating": {
"average": 6.4
}
}, {
"number": "3",
"fileName": "fileXX",
"rating": {
"average": 5.4
}
}, {
"number": "4",
"fileName": "fileXX",
"rating": {
"average": 5.4
}
}]
After sorting, the output would be
[{
"number": "4",
"fileName": "fileXX",
"rating": {
"average": 6.4
}
}, {
"number": "4",
"fileName": "fileXX",
"rating": {
"average": 5.4
}
}, {
"number": "3",
"fileName": "fileXX",
"rating": {
"average": 5.4
}
}]
And after filter, the final result:
[{
"number": "4",
"fileName": "fileXX",
"rating": {
"average": 6.4
}
}, {
"number": "3",
"fileName": "fileXX",
"rating": {
"average": 5.4
}
}]