I am working with a large array in the following format:
// Sample data
const array = [
{country: "Germany", category: "A", value: 300},
{country: "Brazil", category: "A", value: 200},
{country: "Canada", category: "A", value: 200},
{country: "Germany", category: "B", value: 100},
{country: "Brazil", category: "B", value: 400},
{country: "Canada", category: "B", value: 500},
]
and I want to want to rank the values by category and value rank
and potentially add an overall_rank
without considering the category:
// Expected result
[
{country: "Germany", category: "A", value: 300, rank: 1, overall_rank: 2},
{country: "Brazil", category: "A", value: 200, rank: 2, overall_rank: 3},
{country: "Canada", category: "A", value: 200, rank: 2, overall_rank: 3},
{country: "Germany", category: "B", value: 100, rank: 3, overall_rank: 4},
{country: "Brazil", category: "B", value: 200, rank: 2, overall_rank: 3},
{country: "Canada", category: "B", value: 500, rank: 1, overall_rank: 1},
]
So far I got and overall_rank
working, but I am struggling ranking the values by value and category:
var overall_rank = 1;
for (var i = 0; i < array.length; i++) {
if (i > 0 && array[i].value < array[i - 1].value) {
overall_rank++;
}
array[i].overall_rank = overall_rank;
}
How to move forward?
2
Answers
To get the
rank
within the category, you can first useObject.groupBy
to split the objects based on theircategory
property, then sort each of the categories separately.You could sort each record and assign a unique rank:
Or you could group by value: