wittgenstein
wittgenstein

Reputation: 4462

create a new object w/ unique IDs and specific indeces

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:

  1. the object keys of target are the unique entries of the groups array
  2. to get the index of each value of the unique id and save them in an own array

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

Answers (1)

Nina Scholz
Nina Scholz

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

Related Questions