Search code examples
javascriptarraysreactjsobject

how to make an array unique using reduce method of javascript


I have created one example for you to understand the problem.

let arr = [];
arr.push({
  module_id: 41,
  name: 'first'
}, {
  module_id: 41,
  name: 'second',
  important: true,
}, {
  module_id: 43,
  name: 'third'
});

const lookup = arr.reduce((a, e) => {
  a[e.module_id] = ++a[e.module_id] || 0;
  return a;
}, {});
console.log('lookup is', lookup);

let unique = [];
arr.filter((e) => {

  if (lookup[e.module_id] === 0) {
    unique.push(e)
  }
})

console.log('unique', unique)

first, I have an empty array arr and I am pushing 3 objects in it.
Notice, the module_name. There are two repeatings and I'd like to use the second one with the property name important.
I have used reduce here for finding out which one is repeating based on module_name. it'll return 1 with the key of 41 and 0 for 43. I want to use both but I don't want to duplicate into my unique array. Currently, I'll push only those elements which are unique, in our case module_id: 43.
Now how can I get the duplicate value (with important property)?


Solution

  • let arr = [];
    arr.push(
      {
        module_id: 41,
        name: 'first',
      },
      {
        module_id: 41,
        name: 'second',
        important: true,
      },
      {
        module_id: 43,
        name: 'third',
      }
    );
    
    
    const result = arr.reduce(
      (acc, curr) =>
        acc.find((v) => v.module_id === curr.module_id) ? acc : [...acc, curr],
      []
    );
    
    console.log(result);