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

165
Visualizações
filter and sum array of objects in javascript

Hello and thank you for checking my question.

I have an array of objects which contains multiple entries for the same person corresponding to different dates. I need to sum the values for each person.

const data = [
  {
    name: "Bob",
    date: 3/27/22
    value: 300
  },
  {
    name: "Alice",
    date: 1/13/22
    value: 500
  },
  {
    name: "Bob",
    date: 5/13/22
    value: 400
  },
  {
    name: "Alice",
    date: 4/19/22
    value: 350
  },
  {
    name: "John",
    date: 2/15/22
    value: 700
  },
]

I need the result to be:

const result = [
  {
    name: "Bob",
    value: 700
  },
  {
    name: "Alice",
    value: 850
  },
  {
    name: "John",
    value: 700
  },
]

How can I do this in the most efficient way possible?

So far, I have only been able to achieve this by using the filter array method returning the name value, pushing the result to a new array, and summing that array. However, I do not know all of the name values in advance so this wont work.

Thank you for your time

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

0

One way to do this can be this:

const data = [
  {
    name: 'Bob',
    date: '3/27/22',
    value: 300,
  },
  {
    name: 'Alice',
    date: '1/13/22',
    value: 500,
  },
  {
    name: 'Bob',
    date: '5/13/22',
    value: 400,
  },
  {
    name: 'Alice',
    date: '4/19/22',
    value: 350,
  },
  {
    name: 'John',
    date: '2/15/22',
    value: 700,
  },
];

let res = data.reduce((agg, curr) => {
  agg[curr.name] = (agg[curr.name] || 0) + curr.value;
  return agg;
}, {});

const res2 = Object.keys(res).map((v) => {
  return {
    name: v,
    value: res[v],
  };
});

console.log(res2);
about 4 years ago · Juan Pablo Isaza Relatório

0

I think this approach has reasonable performance :

const data = [
  {
    name: "Bob",
    value: 300
  },
  {
    name: "Alice",
    value: 500
  },
  {
    name: "Bob",
    value: 400
  },
  {
    name: "Alice",
    value: 350
  },
  {
    name: "John",
    value: 700
  },
];

const reduceData = (data) => data.reduce((acc, cur) => {
  const {name, value} = cur;                            // Get name and value from current item
  const item = acc.find(it => it.name === name);        // Find in our accumulator the desired object
  item ? item.value += value : acc.push({name, value}); // Update object or create a new object if it doesn't exist
  return acc;                                           // Return accumulator
} , []);

console.log(reduceData(data));

Array.reduce takes an internal function as first parameter.

This internal function usually takes two parameters: one will be the "accumulator" that will be returned by the function and the other will be the "current array item".

Array.reduce will run the internal function on every array item and finally return its value.

The "accumulator" parameter passed to the internal function on every run is the return value of the previous internal function call.

Array.reduce can have an additional parameter which is the initial accumulator value passed to the first internal function call (here we use an empty array).

More info here -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do this by mapping also

const data = [
    {
        name: "Bob",
        date: ' 3 / 27 / 22',
        value: 1,
    },
    {
        name: "Alice",
        date: '1 / 13 / 22',
        value: 2,
    },
    {
        name: "Bob",
        date: '5 / 13 / 22',
        value: 1,
    },
    {
        name: "Alice",
        date: ' 4 / 19 / 22',
        value: 2
    },
    {
        name: "John",
        date: '2 / 15 / 22',
        value: 3
    },
]
const res = {};
for (let i = 0; i < data.length; i++) {

    if (res[data[i].name]) { //here if any key(name) is already present in res then we add the value in already present value of that name
        res[data[i].name].value += data[i].value
    } else {
        res[data[i].name] = data[i] //here we are inserting data into res object if doesn't find any key with already name present in it
    }
}



const res2 = Object.keys(res).map(person => {
    return {
        name: person,
        value: res[person].value
    }
})

console.log(res2);
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