Home > Blockchain >  How to map the items from a list of records contained in an object to a unique array
How to map the items from a list of records contained in an object to a unique array

Time:04-29

I have a list of objects that contain an array as one of the values like so:

const obj_arr = [
{'key': ['value-1', 'value-2', 'value-3', 'value-2', 'value-3']},
{'key': ['value-3', 'value-1', 'value-2', 'value-1', 'value-3']},
{'key': ['value-2', 'value-1', 'value-4', 'value-3', 'value-5']}
];

How do I take this list of values and map only the unique items to an array?

so far I have been able to do this:

const obj_arr = [{
    'key': ['value-1', 'value-2', 'value-3', 'value-2', 'value-3']
  },
  {
    'key': ['value-3', 'value-1', 'value-2', 'value-1', 'value-3']
  },
  {
    'key': ['value-2', 'value-1', 'value-4', 'value-3', 'value-5']
  }
];

let unique_arr = [...new Set(obj_arr.map(record => record['key']))];

console.log(unique_arr);

/*
let unique_arr2 = [...new Set(obj_arr.flatMap(record => record['key']))];
console.log('using guidance from Barmar: ', unique_arr2);
*/
.as-console-wrapper { max-height: 100% !important; top: 0 }

but this only gives me back each unique array like this:

unique_arr = [
['value-1', 'value-2', 'value-3', 'value-2', 'value-3'],
['value-3', 'value-1', 'value-2', 'value-1', 'value-3'],
['value-2', 'value-1', 'value-4', 'value-3', 'value-5']
]

what I actually need is this:

unique_arr = ['value-1', 'value-2', 'value-3', 'value-4', 'value-5']

CodePudding user response:

You could map the values of the objects and get a flat array for the constructor.

const
    array = [{ key: ['value-1', 'value-2', 'value-3', 'value-2', 'value-3'] }, { key: ['value-3', 'value-1', 'value-2', 'value-1', 'value-3'] }, { key: ['value-2', 'value-1', 'value-4', 'value-3', 'value-5'] }],
    unique = [...new Set(array.map(Object.values).flat(Infinity))];

console.log(unique);

CodePudding user response:

I don't know if this is the result you're looking for here is a solution with reduce

let uniqueArrReduce = [...new Set(obj_arr.reduce((acc, el) => [...acc, ...el.key], []) )]

with map and flat

let uniqueArrMapFlat = [...new Set(obj_arr.map(el => el.key).flat())]
  • Related