Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

330
Visualizações
How to compare object values in an array of objects?

I am trying to compare an array of objects. Each object has the same keys, but varying values for each key. I would like to create a function that compares each object for similar key value pairs.

I only care about the quality and location keys for each object, and I want to compare all objects against these two keys.

For example, if the first and second object in the array of objects contains the same value for two keys, I would like to create an output array of objects that summarizes each grouping.

Explanation: Object one and two contain the same value for quality and location. Since the third object does not, a new object should be created that summarizes the information from the first and second objects. That new object should contains an array of all fruit names and and array of all tags. The output object is shown below.

// Input
data = [
  {
    id: '1',
    fruit: 'granny smith',
    quality: 'good',
    location: 'chicago',
    tags: ['green', 'sweet'],
  },
  {
    id: '2',
    fruit: 'Fuji',
    quality: 'good',
    location: 'chicago',
    tags: ['red', 'tart'],
  },
  {
    id: '3',
    fruit: 'gala',
    quality: 'bad',
    location: 'san diego',
    tags: ['tall', 'thin'],
  },
];

// Function
function compareObjects(arr) {
  const grouped = [];

  // Loop over every fruit
  const similarObjects = arr.filter((obj, id) => {
    // create structure for each common object
    let shape = {
      id,
      fruits: [],
      quality: '',
      tags: [],
    };

    arr.forEach((item) => {
      // Return a new shape object that contains all fruit names, tags, and quality
      if (item.quality == obj.quality && item.location == obj.location) {
        shape.id = id;
        shape.fruits.push(item.fruit);
        shape.fruits.push(obj.fruit);
        shape.quality = item.quality;
        shape.tags.push(item.tag);
        shape.tags.push(obj.tag);
        return shape;
      }
    });
    return obj;
  });

  return similarObjects;
}

console.log(compareObjects(data));

// Output
const output = [
  {
    id: 'a',
    fruits: ['grann smith', 'fuji'],
    quality: 'good',
    tags: ['green', 'sweet', 'red', 'tart'],
  },
  ...
];


about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can group the data by their quality and location using Array.prototype.reduce and filter the groups where the length is greater than one.

const 
  data = [
    { id: "1", fruit: "granny smith", quality: "good", location: "chicago", tags: ["green", "sweet"] },
    { id: "2", fruit: "Fuji", quality: "good", location: "chicago", tags: ["red", "tart"] },
    { id: "3", fruit: "gala", quality: "bad", location: "san diego", tags: ["tall", "thin"] },
  ],
  output = Object.values(
    data.reduce((r, d) => {
      const key = `${d.quality}+${d.location}`;
      if (!r[key]) {
        r[key] = { id: d.id, fruits: [], quality: d.quality, location: d.location, tags: [] };
      }
      r[key].fruits.push(d.fruit);
      r[key].tags.push(...d.tags);
      return r;
    }, {})
  ).filter((d) => d.fruits.length > 1);

console.log(output);

If you also wish to only keep unique fruits then you can map over the resultant array and remove the duplicates using a Set.

const 
  data = [
    { id: "1", fruit: "granny smith", quality: "good", location: "chicago", tags: ["green", "sweet"] },
    { id: "2", fruit: "Fuji", quality: "good", location: "chicago", tags: ["red", "tart"] },
    { id: "3", fruit: "gala", quality: "bad", location: "san diego", tags: ["tall", "thin"] },
  ],
  output = Object.values(
    data.reduce((r, d) => {
      const key = `${d.quality}+${d.location}`;
      if (!r[key]) {
        r[key] = { id: d.id, fruits: [], quality: d.quality, location: d.location, tags: [] };
      }
      r[key].fruits.push(d.fruit);
      r[key].tags.push(...d.tags);
      return r;
    }, {})
  )
    .filter((d) => d.fruits.length > 1)
    .map((d) => ({ ...d, fruits: [...new Set(d.fruits)] }));

console.log(output);

Other relevant documentations:

  • Spread syntax (...)
  • Array.prototype.push
  • Array.prototype.filter
  • Object.values
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda