Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda