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

187
Visualizações
How to sum duplicated values inside array in order

I need some help to sum values inside an array in order

I have two arrays:

array1 = ['car', 'car', 'ball', 'piano', 'car'] 
array2 = ['2500', '1000', '400', '2500', '4500']

I'm using this code below to remove the duplicated values inside array1:

var uniqueValues = [];
for(var i in array1){
    if(uniqueValues.indexOf(array1[i]) === -1){
       uniqueValues.push(array1[i]);
    }
}

//returns ['car', 'ball', 'piano'] 

What I need is to sum the values of array2 using the order of array1, so I will have this result:

result = ['8000', '400', '2500']

So the final result would be this:

array1 = ['car', 'ball', 'piano'] 
array2 = ['8000', '400', '2500']

Any suggestion ? thank you.

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

0

(1) Use Array#reduce() and Object.assign() to build an object with unique keys (and values summed):

{ car: 8000, ball: 400, piano: 2500 }

(2) Use Object.keys() to get new array1:

[ 'car', 'ball', 'piano' ]

(3) Use Object.values() to get new array2:

[ 8000, 400, 2500 ]

DEMO 1

let array1 = ['car', 'car', 'ball', 'piano', 'car'];
let array2 = ['2500', '1000', '400', '2500', '4500'];

const result = array1.reduce((acc, cur, index) => Object.assign(acc, {
    [cur]: (acc[cur] || 0) + +array2[index]
}), {});

array1 = Object.keys(result);
array2 = Object.values(result);

console.log(array1);
console.log(array2);

You can also return an object literal directly in Array#reduce() as follows:

const result = array1.reduce((acc, cur, index) => ({
    ...acc,
    [cur]: ((acc[cur] || 0) + +array2[index])
}), {});

DEMO 2

let array1 = ['car', 'car', 'ball', 'piano', 'car'];
let array2 = ['2500', '1000', '400', '2500', '4500'];

const result = array1.reduce((acc,cur,index) => ({...acc,[cur]:((acc[cur] || 0) + +array2[index])}), {});

array1 = Object.keys(result);
array2 = Object.values(result);

console.log(array1);
console.log(array2);

about 4 years ago · Juan Pablo Isaza Relatório

0

Reduce will do the trick

NOTE Does JavaScript guarantee object property order?

let array1 = ['car', 'car', 'ball', 'piano', 'car'] 
let array2 = ['2500', '1000', '400', '2500', '4500']

const merged = array1.reduce((acc,cur,i) => {
  acc[cur] = (acc[cur] || 0) + +array2[i]; // add after casting to number
  return acc
},{})

console.log(merged)

array1 = Object.keys(merged)
array2 =  Object.values(merged)

console.log(array1)
console.log(array2)

about 4 years ago · Juan Pablo Isaza Relatório

0

Not exactly the best solution, but should work. I have used the map to create an index and add the values. It is a simple one.

let array1 = ['car', 'car', 'ball', 'piano', 'car', 'ball', 'piano'];
let array2 = ['2500', '1000', '400', '2500', '4500', '2500', '4500'];
const MapOfItems = new Map();
array1.forEach(function(item, index) {
  if (MapOfItems.has(item))
    MapOfItems.set(item, MapOfItems.get(item) + +array2[index]);
  else
    MapOfItems.set(item, +array2[index]);
});

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