skip to Main Content

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


  1. 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.

    const map = new Map();
    map.set('a', a);
    map.set('b', b);
    map.set('c', c);
    
    const result = [];
    const names = new Set();
    map.entries().forEach(([key, array]) =>
      array.forEach(({
        data
      }) => {
        if (!names.has(data[0])) {
          names.add(data[0]);
          result.push(data);
        }
      })
    );
    
    console.log(result);
    <script>
      const a = [{
        data: ['name1', true, true]
      }, {
        data: ['name2', false, true]
      }];
      const b = [{
        data: ['name3', true, true]
      }, {
        data: ['name2', false, true]
      }];
      const c = [];
    </script>
    Login or Signup to reply.
  2. One option is to map your array of data into an array of arrays with .flatMap() and .map(), giving you:

    [['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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search