Jeet
Jeet

Reputation: 795

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

Upvotes: 2

Views: 2812

Answers (4)

Manav.J
Manav.J

Reputation: 1

const arr = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5];
const uniqueNums = arr.reduce( (all,item) => {
  if(all.indexOf(item) === -1) {
    all.push(item)
  }
  return all
},[])

Upvotes: 0

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

Upvotes: 3

Timsib Adnap
Timsib Adnap

Reputation: 542

try

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

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

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

Upvotes: 1

Related Questions