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

178
Visualizações
Map through array of objects and add counter of elements with the same property value

Given following array:

const arr = [
  {color: 'red'}, 
  {color: 'red'}, 
  {color: 'green'}, 
  {color: 'blue'}, 
  {color: 'blue'}, 
  {color: 'red'}]

how to map through its element to create an array of objects extended with property colorIndex which would work as a counter of how many previous elements have the same color property?

the result would be a following array:

[
  {color: 'red', colorIndex: 0}, 
  {color: 'red', colorIndex: 1}, 
  {color: 'green', colorIndex: 0}, 
  {color: 'blue', colorIndex: 0}, 
  {color: 'blue', colorIndex: 1}, 
  {color: 'red', colorIndex: 2}
]

is there some elegant solution to achieve that?

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

0

Edit:

Based on @FZs comment, I'm posting much faster (and more clear) solution. It requires much less operations to complete and much less "brain power" (aka cognitive load) to read it ;)

const arr = [
    { color: 'red' },
    { color: 'red' },
    { color: 'green' },
    { color: 'blue' },
    { color: 'blue' },
    { color: 'red' }
]

var countByColor = new Map();

console.log(
    arr.map(function mapArray(elem, index) {
        var color = elem.color;
        var count = countByColor.get(color) || 0;
        countByColor.set(color, count + 1); // add 1, so next time we spot the color it will get correct counter

        return {
            color, count
        }
    })
)

Old vs new perf test: https://jsbench.me/7kkx5zffpm/2


Original answer:

Well, not sure why are you asking and what have you tried already to solve this. It's hard to get proper answer where there is no context at all. But here is my approach, maybe you'll lern a bit of it:

arr.map((elem, index) => {

  // we only care about values before current index, to see how many elements with given color were **before**
  var colors = arr.map((obj) => obj.color).splice(0, index + 1);

  return {
    ...elem, // using spread operator to get all properties of original object
    count: colors.reduce(
      (prev, curr) => (curr == elem.color ? prev + 1 : prev),
      -1 // starting from -1 to get 0-based counter
    ),
  };
})

See it on stackblitz here: https://stackblitz.com/edit/js-bnru4m

Read more about reduce: https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Read more about spread operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Read more about splicing an array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Read more about mapping an array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

about 4 years ago · Juan Pablo Isaza Relatório

0

The first solution that comes to my mind isn't elegant but it will do the trick. Best is to work with and extra object.

const foundItems = {};

arr.map(item => {
   let foundItem = foundItems[item.color] ? foundItems[item.color]+ 1 : 0;
   foundItems[item.color] = founditem;
   return {
      ...item,
      colorIndex: foundItem,
   }

})
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