(Each step gets the output of the previous step. Everything will be put together in the end.)
Step 1: Get a map of sums
You can transform this:
[
{ country: 'France', value: 100 },
{ country: 'France', value: 100 },
{ country: 'Romania', value: 500 },
{ country: 'England', value: 400 },
{ country: 'England', value: 400 },
{ country: 'Spain', value: 130 },
{ country: 'Albania', value: 4 },
{ country: 'Hungary', value: 3 }
]
into this:
{
Albania: 4,
England: 800,
France: 200,
Hungary: 3,
Romania: 500,
Spain: 130
}
With this:
const reducer = reduceBy((sum, {value}) => sum + value, 0);
const reduceCountries = reducer(prop('country'));
Step 2: Convert that back into a sorted array
[
{ country: "Hungary", value: 3 },
{ country: "Albania", value: 4 },
{ country: "Spain", value: 130 },
{ country: "France", value: 200 },
{ country: "Romania", value: 500 },
{ country: "England", value: 800 }
]
You can do this with:
const countryFromPair = ([country, value]) => ({country, value});
pipe(toPairs, map(countryFromPair), sortBy(prop('value')));
Step 3: Create two sub groups, the non-top-4 countries and the top-4 countries
[
[
{ country: "Hungary", value: 3},
{ country: "Albania", value: 4}
],
[
{ country: "Spain", value: 130 },
{ country: "France", value: 200 },
{ country: "Romania", value: 500 },
{ country: "England", value: 800 }
]
]
Which you can do with this:
splitAt(-4)
Step 4: Merge the first sub group
[
[
{ country: "Others", value: 7 }
],
[
{ country: "Spain", value: 130 },
{ country: "France", value: 200 },
{ country: "Romania", value: 500 },
{ country: "England", value: 800 }
]
]
With this:
over(lensIndex(0), compose(map(countryFromPair), toPairs, reduceOthers));
Step 5: Flatten the entire array
[
{ country: "Others", value: 7 },
{ country: "Spain", value: 130 },
{ country: "France", value: 200 },
{ country: "Romania", value: 500 },
{ country: "England", value: 800 }
]
With
flatten
Complete working example
const data = [
{ country: 'France', value: 100 },
{ country: 'France', value: 100 },
{ country: 'Romania', value: 500 },
{ country: 'England', value: 400 },
{ country: 'England', value: 400 },
{ country: 'Spain', value: 130 },
{ country: 'Albania', value: 4 },
{ country: 'Hungary', value: 3 }
];
const reducer = reduceBy((sum, {value}) => sum + value, 0);
const reduceOthers = reducer(always('Others'));
const reduceCountries = reducer(prop('country'));
const countryFromPair = ([country, value]) => ({country, value});
const top5 = pipe(
reduceCountries,
toPairs,
map(countryFromPair),
sortBy(prop('value')),
splitAt(-4),
over(lensIndex(0), compose(map(countryFromPair), toPairs, reduceOthers)),
flatten
);
top5(data)