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

91
Visualizações
Convert an array of numbers into key followed by indices which match the key

New to JavaScript. I am trying to convert an array of numbers

[ 12,14,12,10,11,10 ]

into an object array with the key as the number in the array followed by an array of indices where the number occurs such as

{'12': [0, 2]], '10': [3,5], '11': 4 }

I saw several examples with reduce but I don't understand how to create the array of items for a given key.

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

0

You can use Array#reduce with an object as the accumulator.

The callback is given the previous accumulator, the current array element, and its index. We can initialize the property for the current element's value to an empty array if not already set with the logical nullish assignment operator before adding the current index to that array.

let arr = [ 12,14,12,10,11,10 ];
let res = arr.reduce((acc, curr, i)=>
    ((acc[curr] ??= []).push(i), acc), {});
console.log(res);
.as-console-wrapper{max-height:100%!important}

about 4 years ago · Juan Pablo Isaza Relatório

0

You can easily achive the result using Map in for..of loop

const arr = [12, 14, 12, 10, 11, 10];

const map = new Map();
arr.forEach((n, i) => (map.has(n) ? map.get(n).push(i) : map.set(n, [i])));

const result = {};
for (let [k, v] of map) {
  v.length === 1 ? (result[k] = v[0]) : (result[k] = v);
}

console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

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