Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

85
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda