I have a Map in the following format.
const a = [{ data: ['name1', true, true] }, { data: ['name2', false, true] }];
const b = [{ data: ['name3', true, true] }, { data: ['name2', false, true] }];
const c = [];
const map = new Map();
map.set('a', a);
map.set('b', b);
map.set('c', c);
const expectedData = [
['name1', true, true],
['name2', false, true],
['name3', true, true],
]; // remove duplicates and empty arrays. name2 is included only once in the final array
I tried using the spread operator and creating a new set of elements. But the final array includes all the occurrences of ‘name2’ such as: [[‘name1’, true, true], [‘name2’, false, true], [‘name2’, false, true], [‘name3’, true, true]].
Is there an easy way to filter the map’s values based on the first element of the array?
2
Answers
Loop over all the objects in the map. Use a
Set
to hold the names that have been added to the result, so you only add a name once.One option is to map your array of data into an array of arrays with
.flatMap()
and.map()
, giving you:and then using
Map.groupBy()
on this array to create a Map grouped by the first element (name). Once you have this group, you can useArray.from()
to get the first unique name entry and convert the map into an array: