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
JavaScript
x
18
18
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}]
2
data.sort();
3
let map= new Map()
4
for(let ele of data){
5
if(map.has(ele)){
6
map.set(ele,map.get(ele)+1)
7
}else{
8
map.set(ele,1)
9
}
10
}
11
console.log(map)
12
let arr = []
13
for(let[key,value]of map){
14
key.count=value
15
arr.push(key)
16
}
17
console.log(arr)
18
I also do an iteration of the data array, but the same problem occurs.
JavaScript
1
13
13
1
let arr=[]
2
let count = 1
3
data[0].count = count
4
for(let i = 1; i < data.length; i ++){
5
if(data[i]==data[i-1]){
6
arr[arr.length-1].count++
7
} else{
8
data[i].count = 1
9
arr.push(data[i])
10
11
}
12
}
13
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.
JavaScript
1
17
17
1
const isSameObj = (obj1, obj2) => (
2
Object.keys(obj1).length === Object.keys(obj2).length &&
3
Object.entries(obj1).every(([key, val]) => obj2.hasOwnProperty(key) && obj2[key] === val)
4
);
5
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 }];
6
const map = new Map();
7
for (const obj1 of data) {
8
const foundObj = [map.keys()].find(obj2 => isSameObj(obj1, obj2));
9
if (foundObj) {
10
map.set(foundObj, map.get(foundObj) + 1);
11
} else {
12
map.set(obj1, 1);
13
}
14
}
15
const output = [map.entries()]
16
.map(([obj, count]) => ({ obj, count }));
17
console.log(output);