Search code examples
javascriptarrays

How to get unique values from an array of objects in a Map?


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?


Solution

  • One option is to map your array of data into an array of arrays with .flatMap() and .map(), giving you an array of this shape:

    [['name1', true, true], ['name2', false, true], ['name3', true, true], ...]
    

    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 use Array.from() to get the first unique name entry and convert the Map into an array:

    const a = [{ data: ['name1', true, true] }, { data: ['name2', false, true] }];
    const b = [{ data: ['name3', true, true] }, { data: ['name2', false, true] }];
    const c = [];
    
    const arrays = [a, b, c];
    
    const grouped = Map.groupBy(arrays.flatMap(arr => arr.map(o => o.data)), ([name]) => name);
    const res = Array.from(grouped, ([,[first]]) => first);
    console.log(res);