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.
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}
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; }