Search code examples
javascriptarraysfiltertrim

How can i filter and modify each object in array in javascript?


I'm developing a little webapp which receives an array of objects from an api and then shows the result on the page after adding some data to each object and deleting other objects.

I have tried by chechink if the current index element is the same as the nexts but for some reason it doesn't work.

const initialArray = [
{ x: 'one', y: 'place1'},
{ x: 'one', y: 'place1'},
{ x: 'two', y: 'place2'},
{ x: 'three', y: 'place3'},
{ x: 'three', y: 'place3'},
{ x: 'three', y: 'place3'},
{ x: 'four', y: 'place4'}
]

The expected result should be:

let resArray = [
{ x: 'one' , y: 'place1', count: 2},
{ x: 'two', y: 'place2', count: 1 },
{ x: 'three', y: 'place3', count: 3 },
{ x: 'four', y: 'place4', count: 1 }
]

console doesn't give any error so it means my algorithm was incorrect. Thanks for the support


Solution

  • You can use reduce()

    const initialArray = [
      { x: 'one', y: 'place1'},
      { x: 'one', y: 'place1'},
      { x: 'two', y: 'place2'},
      { x: 'three', y: 'place3'},
      { x: 'three', y: 'place3'},
      { x: 'three', y: 'place3'},
      { x: 'four', y: 'place4'}
    ];
    
    const res = initialArray.reduce((ac,{x,y}) => {
      let k = `${x}_${y}`
      if(!ac[k]) ac[k] = {x,y,count:0};
      ac[k].count++;
      return ac;
    
    
    },{})
    console.log(Object.values(res))