Home > Software design >  How to check if an object exists in an *empty* Array
How to check if an object exists in an *empty* Array

Time:03-01

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related