find total number of elements in between the numbers 0 t0 10, 10 to 20, 20 to 30 and so on in an array. say the array [23,14,67,17,87] so there are 0 numbers from 0 to 10, 2 numbers from 10 to 20, and so on.
CodePudding user response:
This crux of the logic:
const data = [23,14,67,17,87];
console.log(
data.reduce((results, entry) => {
// We only are interested in the 10s unit; the 1s don't matter.
// This discards the 1s unit, and homologates numbers of the same multiple
// of 10, e.g.
// 14 → 1
// 17 → 1
const factor = Math.floor(entry / 10);
// Create a human readable key, i.e 10 to 20
const key = `${factor * 10} to ${(factor * 10) 10}`
return {
...results,
// If the group has not already been added to the results,
// this will set the value to 1, otherwise increment by 1.
[key]: (results[key] ?? 0) 1,
};
}, {})
);
You can always sort the groups if needed.