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

212
Visualizações
merge values together in a 2d array

having a little bit of an issue trying to merge values in a 2d array.

For example:

const formatBids = 
 [
   [4444, 10000],
   [4444, 500],
   [4455, 500],
 ];

I want to sum up the 2nd param of the array if the first param are the same, so the end result being:

 [
   [4444, 10500],
   [4455, 500],
 ];

i have tried the following but its continually adding to itself producing the wrong results:

formatBids.map(bid => {
  const map = new Map([bid]);
  formatBids.forEach(arr => (arr[1] += map.get(arr[0]) ?? 0));
});

unsure the best way to tackle this. Ideas?

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

0

You could just use an Object as a sort of map and use the first item in an array as the key. Then you can convert it back to an Array using Object.entries(). Like so:

const formatBids = 
 [
   [4444, 10000],
   [4444, 500],
   [4455, 500],
 ];
 
const totals = {}

for (const bid of formatBids) {
  totals[bid[0]] = (totals[bid[0]] || 0) + bid[1];
}

console.log("as object:", totals, "as array:", Object.entries(totals));

about 4 years ago · Juan Pablo Isaza Relatório

0

const formatBids = [
  [4444, 10000],
  [4444, 500],
  [4455, 500],
];

let merged = {}

formatBids.forEach((ele) => {
  let key = parseInt(ele[0]);
   merged[key] = (merged[key] ?? 0)+ele[1];
})

let mergedArr = Object.entries(merged);
console.log(mergedArr)

This is the another way of doing this

  1. Sort the array based on first index
  2. Push into array if currentArr(merged Array) is empty.
  3. If not empty, then check the first element at last index of currentArr is equal to the first index of CurrentElement.
    • if yes, then add the 2nd element value to the currentArr's[n-1][1]
    • else, insert currentElement into the currentArr

const formatBids = [
  [4444, 10000],
  [4444, 500],
  [4455, 500],
];
var mergedArr = formatBids.sort().reduce((currentArr, currentElement) => {
  let n = currentArr.length;
  if (n === 0) return [currentElement];

  if (currentElement[0] === currentArr[n - 1][0]) {
    currentArr[n - 1][1] += currentElement[1];
    return currentArr;
  } else return [...currentArr, currentElement];
}, []);
console.log(mergedArr)

about 4 years ago · Juan Pablo Isaza Relatório

0

const formatBids = 
 [
   [4444, 10000],
   [4444, 500],
   [4455, 500],
 ];
 
const result = Object.entries(formatBids.reduce((acc, [key, value]) => {
   if (!acc[key]) acc[key] = value;
   else acc[key] += value;
   return acc;
}, {}));

console.log(result);

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