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

296
Views
How to check if an object exists in an *empty* Array

I have an empty array

const someArray = []

and then I have another array of 2 objects (can vary)

let users = [
    {
        id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
        name: 'John Doe',
        age: 50,
    },
    {
        id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
        name: 'Jane Doe',
        age: 45,
    },
];

the id key which make users unique.

As you can see I have 2 users with same id I only want to add the first one. What I did so far

users.forEach((user) => {
  if (!someArray.includes(user.id)) {
    someArray.push(user);
  }
});

// OTHER METHOD I USED
users.forEach((user) => {
  if (someArray.some((element) => element.id !== user.id)) {
    someArray.push(user);
  }
});

The first method appending both elements even thier id's are same and the second method is doing nothing or is not appending anything.

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

0

You could keep a map with the ids that you already added, and only add it if the key is missing:

const ids = {};

users.forEach(user => {
 if (!ids[user.id]) {
  someArray.push(user);
  ids[user.id] = true;
 }
})
about 4 years ago · Juan Pablo Isaza Report

0

using reduce would work for your case

let users = [{
    id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
    name: 'John Doe',
    age: 50,
  },
  {
    id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
    name: 'Jane Doe',
    age: 45,
  },
  {
    id: '8c919536-ccb5-4c3b-b599-36dc716b7478',
    name: 'Jane Doe',
    age: 45,
  },
];

var result = users.reduce((prev, curr) => {
  if (prev.find(i => i.id == curr.id)) return prev
  return [...prev, 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!