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?