1

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

1
  • 1
    please provide also the actual code Commented Jun 22, 2019 at 10:28

1 Answer 1

2

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))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.