Suppose, we have an array of objects that contains some like this −
const arr = [
{'item1': 144},
{'item2': 0},
{'item3': 366},
{'item4': 15},
{'item6': 366},
{'item7': 19},
{'item8': 211},
{'item9': 121}
];We are required to write a JavaScript function that takes in one such array and clusters the objects into four groups namely −
'XL', 'L', 'M', 'S'
Numbers should be distributed in these groups on the basis of their relative magnitude.
Example
The code for this will be −
const arr = [
{'item1': 144},
{'item2': 0},
{'item3': 366},
{'item4': 15},
{'item6': 366},
{'item7': 19},
{'item8': 211},
{'item9': 121}
];
const compareWithRange = (rangeArr, num) => {
for(let i = 0; i < rangeArr.length; i++){
if(num <= rangeArr[i] && num > rangeArr[i + 1]){
return i;
};
};
return rangeArr.length - 1;
}
const groupBySize = (arr = []) => {
const mapping = arr => arr.map(el => el[Object.keys(el)[0]]);
const max = Math.max(...mapping(arr));
const range = {
'XL': max,
'L': (max * 3) / 4,
'M': (max / 2),
'S': (max / 4)
};
const legend = ['XL', 'L', 'M', 'S'];
const res = {};
arr.forEach(el => {
const num = el[Object.keys(el)[0]];
const index = compareWithRange(Object.keys(range).map(key => range[key]), num);
const size = legend[index];
if(res.hasOwnProperty(size)){
res[size].push(Object.keys(el));
}
else{
res[size] = [Object.keys(el)];
}
});
return res;
};
console.log(groupBySize(arr));Output
And the output in the console will be −
{
M: [ [ 'item1' ], [ 'item9' ] ],
S: [ [ 'item2' ], [ 'item4' ], [ 'item7' ] ],
XL: [ [ 'item3' ], [ 'item6' ] ],
L: [ [ 'item8' ] ]
}