Home > Software engineering >  how to make an array unique using reduce method of javascript
how to make an array unique using reduce method of javascript

Time:12-22

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)?

CodePudding user response:

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);

CodePudding user response:

You could take a Map and get only distinct first values or the ones with important flag.

const
    array = [{ module_id: 41, name: 'first' }, { module_id: 41, name: 'second', important: true }, { module_id: 43, name: 'third' }],
    result = Array.from(array
        .reduce(
            (m, o) => m.set(o.module_id, !o.important && m.get(o.module_id) || o),
            new Map
        )
        .values()
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

try

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

  if (lookup[e.module_id] === 0) {
    unique.push(e)
  }
  else if (e.important) {
    unique.push(e)
  }
})
  • Related