Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

try

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

  if (lookup[e.module_id] === 0) {
    unique.push(e)
  }
  else if (e.important) {
    unique.push(e)
  }
})
about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!