Reputation: 4462
I want a clean way to create a new object from the given data:
const groups = [1, 2, null, 1, 1, null]
here is my target:
// key = unique id, value = index of unique id in groups
const target = {
null: [2, 5],
1: [0, 3, 4],
2: [1]
}
I try to reach:
my current approach:
const groupIDs = [1, 2, null, 1, 1, null]
const group = {}
const uniqueIDs = [...new Set(groupIDs)]
uniqueIDs.forEach(uid => {
const arr = groupIDs.map((id, idx) => uid === id ? idx : null)
const filtered = arr.filter(idx => idx !== null)
Object.assign(group, { [uid]: filtered })
})
Upvotes: 1
Views: 38
Reputation: 386550
You could reduce the array directly by using an object as accumulator and take the values as key and the indices as value for the grouped arrays.
This approach features an logical nullish assignment ??=
where the right side is assigned to the left, if the LHS is undefined
or null
.
const
groups = [1, 2, null, 1, 1, null],
target = groups.reduce((r, value, index) => {
r[value] ??= [];
r[value].push(index);
return r;
}, {});
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1