Skip to content Skip to sidebar Skip to footer

How To Count Duplicate Object In Js

im trying to add counting number for duplicate in JS. and i am completely stack in this case below. i need to compare objects with two value (x, y) and if there are same values of

Solution 1:

use .reduce() function

const data = [
    {id: 1, x: 1, y: 1},
    {id: 2, x: 2, y: 2},
    {id: 3, x: 1, y: 1},
]

const output = data.reduce((acc, curr) => {
  curr.count = 1;
  const exists = acc.find(o => o.x === curr.x && o.y === curr.y);
  
  exists ? exists.count++ : acc.push(({ x, y, count } = curr));
  
  return acc;
}, []);

console.log(output);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Solution 2:

One way of doing so, is to create a map with the x and y values, and increment the count accordingly, then convert the map into an array:

const data = [
        {id: 1, x: 1, y: 1},
        {id: 2, x: 2, y: 2},
        {id: 3, x: 1, y: 1},
    ]
    
    constmakeXYMap =  (data) => data.reduce((acc, cur) => {
      const { x, y } = cur;
      const entry = acc[`${x}_${y}`];
      
      if (entry) {
    	acc[`${x}_${y}`] = {...entry, count: entry.count + 1};
      } else {
      	acc[`${x}_${y}`] = { x, y, count: 1 };
      }
    
      return acc;
    }, {});
    
    constmakeArray = (XYMap) => Object.values(XYMap);
    
    console.log(makeArray(makeXYMap(data)));

Note that complexity wise, this solution is a O(N).

https://jsfiddle.net/9o35neg7/

Solution 3:

const data = [
  { id: 1, x: 1, y: 1 },
  { id: 2, x: 2, y: 2 },
  { id: 3, x: 1, y: 1 },
  // .. so on ..
];

const countedData = data.reduce((acc, { x, y }, index, array) => {
  acc[`x${x}y${y}`] = {
    x,
    y,
    count: (acc[`x${x}y${y}`] ? acc[`x${x}y${y}`].count : 0) + 1
  };

  return index === (array.length - 1) ? Object.values(acc) : acc;
}, {});

console.log(countedData);

Solution 4:

Use forEach and build an object with key (made of x, y) and values (aggregate count). Get the Object.values to get the results as array.

const data = [
    {id: 1, x: 1, y: 1},
    {id: 2, x: 2, y: 2},
    {id: 3, x: 1, y: 1},
]

constcounts = (arr, res = {}) => {
  arr.forEach(({x , y}) => 
    res[`${x}-${y}`] = { x, y, count: (res[`${x}-${y}`]?.count ?? 0) + 1 })
  returnObject.values(res);
}

console.log(counts(data))

Post a Comment for "How To Count Duplicate Object In Js"