Input:
[
{ x: 'a', order: 10},
{ x: 'a', order: 3},
{ x: 'a', order: 4},
{ x: 'b', order: 3},
{ x: 'b', order: 2},
{ x: 'b', order: 1}
]
Output :
{
โa":[{"x":"a","order":10},{"x":"a","order":3},{"x":"a","order":4}],
โb":[{"x":"b","order":3},{"x":"b","order":2},{"x":"b","order":1}]
}
Solution:
const arr = [
{ x: 'a', order: 10},
{ x: 'a', order: 3},
{ x: 'a', order: 4},
{ x: 'b', order: 3},
{ x: 'b', order: 2},
{ x: 'b', order: 1}
];
function formatArray(input){
output = {};
input.forEach( (value)=>{
const xValue = value.x;
if(Object.keys(output).includes(xValue+'')){
output[xValue].push(value);
}else{
output[xValue] = [value];
}
});
return output;
}
console.log("output",formatArray(arr));
Top comments (0)