DEV Community 👩‍💻👨‍💻

pampapati
pampapati

Posted on

Format Array : JavaScript

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));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.