Skip to content
Advertisement

Javascript coding, combine the same object

data = [{a:1, b:2},{a:2, b:2},{a:2, b:2},{a:3, b:2},{a:3, b:2},{a:3, b:2}], we need to convert data array to data = [{a:1, b:2, count:1},{a:2, b:2, count:2},{a:3, b:2, count:3}]

I used this code, but it seems the key to the map is deep comparison. so even with the same string value, I got different keys

  data = [{a:1, b:2},{a:2, b:2},{a:2, b:2},{a:3, b:2},{a:3, b:2},{a:3, b:2}]
data.sort();
let map= new Map()
for(let ele of data){
    if(map.has(ele)){
        map.set(ele,map.get(ele)+1)
    }else{
        map.set(ele,1)
    }
}
console.log(map)
let arr = []
for(let[key,value]of map){
    key.count=value
    arr.push(key)
}
console.log(arr)

I also do an iteration of the data array, but the same problem occurs.

let arr=[]
let count = 1
data[0].count = count
for(let i = 1; i < data.length; i ++){
  if(data[i]==data[i-1]){
      arr[arr.length-1].count++
  } else{
      data[i].count = 1
      arr.push(data[i])

  }
}

So is there a better way to duel with it?

Advertisement

Answer

Comparing objects will require checking that the number of keys is the same, and that each key-value pair exists in both. It’ll require a bit of boilerplate.

const isSameObj = (obj1, obj2) => (
    Object.keys(obj1).length === Object.keys(obj2).length &&
    Object.entries(obj1).every(([key, val]) => obj2.hasOwnProperty(key) && obj2[key] === val)
);
const data = [{ a: 1, b: 2 }, { a: 2, b: 2 }, { a: 2, b: 2 }, { a: 3, b: 2 }, { a: 3, b: 2 }, { a: 3, b: 2 }];
const map = new Map();
for (const obj1 of data) {
    const foundObj = [...map.keys()].find(obj2 => isSameObj(obj1, obj2));
    if (foundObj) {
        map.set(foundObj, map.get(foundObj) + 1);
    } else {
        map.set(obj1, 1);
    }
}
const output = [...map.entries()]
    .map(([obj, count]) => ({ ...obj, count }));
console.log(output);
Advertisement