1

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?

1 Answer 1

2

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

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

3 Comments

Thanks so much! I rewrote your code and am using the const isSameObj = (obj1, obj2) => {...} but got the wrong answer, may I ask the difference between isSameObj = (obj1, obj2) => {...} and isSameObj = (obj1, obj2) => (...)?
=> { creates a function block. You must use return to return an expression at the end of a block. => ( is implicit return, whatever's inside the ()s gets returned, without requiring a return statement
When an answer solves your problem, you may consider upvoting and/or marking it as Accepted (check the checkbox on the left) to indicate that the issue is resolved :)

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.