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

162
Visualizações
Using reduce inside map

Whenever I'd like to use reduce inside a map function I get the error 'reduce is not a function'.

I've got an array where I'm mapping through 2 keys. Date and Amount. Below is the array with objects.

const dividendArrayFiltered = [
    {
        "date": "2021-11-09",
        "amount": 0.5
    },
    {
        "date": "2021-11-08",
        "amount": 0.5
    },
    {
        "date": "2021-11-08",
        "amount": 0.5
    },
    {
        "date": "2021-11-11",
        "amount": 1
    },
    {
        "date": "2021-11-11",
        "amount": 1
    }
]

Within this map I'd like to reduce the values with the same date.

This is the code that is giving the error. Not quite sure why the reduce function is not working. Hope you could help me out. Thanks!

const summedDividend = dividendArrayFiltered.map(({ date, amount }) => {
    const grouped = date.reduce(
      (a, d, i) => a.set(d, (a.get(d) ?? 0) + amount[i]),
      new Map()
    );

    return {
      date: [...grouped.keys()],
      amount: [...grouped.values()],
    };
  });
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your own solution isn't working because inside the map-function you have only access on the current item, not the array, but the reduce-function can only be used on arrays.

Alternative Solution:

You can create an empty array, where you push only these items from your origin array, which haven't the same date like one of the items in your new array.

  let uniqueArray = [] 

  // iterate through all array elements
  dividendArrayFiltered.forEach((item) => {
    // check if an element with the current item date exists in your new uniqueArray and which position index it has
    const itemPos = uniqueArray.findIndex(uniqueItem => uniqueItem.date == item.date)
    // if the index is negative, it's not included in the array, so you push your item to the new array
    if(itemPos < 0) {
      uniqueArray.push(item)
    }
    // if it's included, you take the old amount and add your new value
    else {
      uniqueArray[itemPos].amount = uniqueArray[itemPos].amount + item.amount;
    }
  });

  console.log(uniqueArray);

In uniqueArray are now only unique date items.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can reduce the original array directly and also utilize findIndex():

const dividendArrayFiltered = [
  { date: '2021-11-09', amount: 0.5 },
  { date: '2021-11-08', amount: 0.5 },
  { date: '2021-11-08', amount: 0.5 },
  { date: '2021-11-11', amount: 1 },
  { date: '2021-11-11', amount: 1 }
]

const grouped = dividendArrayFiltered.reduce((a, c) => {
  const dateIndex = a.findIndex(o => o.date === c.date)
  if (dateIndex !== -1) a[dateIndex].amount += c.amount
  else a.push({ date: c.date, amount: c.amount })

  return a
}, [])

console.log(grouped)
.as-console-wrapper { min-height: 100% }

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