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

119
Views
Return array of objects with respect to uniqueness of property: Javascript

I am having array of objects with the following structure

const arr = [
              {id: 0, name: "abc", userid: "0"},
              {id: 1, name: "lmn", userid: "123"},
              {id: 3, name: "pqr", userid:"456"},
              {id: 4, name: "xyz", userid: "123"}
            ]

I want to return the objects where userid should be unique and is not equals to "0".

This is my approach. It returns just everything

   const result = [
        ...new Set(
             arr.map((node) => {
            if (node.userid !== "0") return node;
          })
        )
      ];
      console.log(result);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Instead of using Set, use Map. Both are used to store unique values, the difference between them is Set for arrays with unique values while Map for objects with unique keys.

const arr = [
  {id: 0, name: "abc", userid: "0"},
  {id: 1, name: "lmn", userid: "123"},
  {id: 3, name: "pqr", userid: "456"},
  {id: 4, name: "xyz", userid: "123"}
];
const result = new Map()
arr.forEach(node => {
  if(node.userid !== "0"){
    result.set(node.userid,node);
  }
})
console.log([...result.values()]); // log intended results

For shorthanded solution you can use:

const result = [...new Map(arr.filter(node=>node.userid!=="0").map(node=>[node.userid, node])).values()];
console.log(result) // log intended results
about 4 years ago · Juan Pablo Isaza Report

0

Maybe that might me done in a more short-hand way, but it works this way:

const arr = [
          {id: 0, name: "abc", userid: "0"},
          {id: 1, name: "lmn", userid: "123"},
          {id: 3, name: "pqr", userid: "456"},
          {id: 4, name: "xyz", userid: "123"}
        ];

const clearZero = arr.filter((obj) => obj.id != 0);
const finalArray = [];

clearZero.forEach((obj) => {
  if (finalArray.every((elem) => elem.userid !== obj.userid)) {
    finalArray.push(obj);
  }
})

console.log(finalArray); // logs out no. 1 and no.3
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!