1

I have a problem to prevent adding new object to array which has the same value of id like existing element of object in array. My array is like this:

var arr = [
       {id:1, name:'Fabricio'},
       {id:2, name:'Leontina'},
       {id:3, name:'Rodrigo'}];

If I want to add object like this {id:2; name:'Evander'}, that couldn't be done because of id.

3 Answers 3

9

You can check if an id is in the array as:

if(!arr.some(el => el.id === 2))
  arr.push({ id: 2, name: "Evander" });

But actually this is a good usecase for a Map:

const users = new Map([
 [1, { name: "one" }],
 [2, { name: "two" }]
]);

So you can easily check if an id is already there in constant time:

if(!users.has(2))
  users.set(2, { name: "newtwo" });
Sign up to request clarification or add additional context in comments.

3 Comments

Muchas gracias!
@opie de nada! :)
You could also keep the id inside the object, assuming it has some value outside being a primary key: const users = new Map( arr.map( o => [o.id, o] ) ). With thanks to @JonasW. for the reminder about map.
4

You can use Array#find:

const arr = [
       {id:1, name:'Fabricio'},
       {id:2, name:'Leontina'},
       {id:3, name:'Rodrigo'}
];

function push(array, item) {
  if (!array.find(({id}) => id === item.id)) {
    array.push(item);
  }
}

push(arr, {id: 2, name: 'Evander'}); // won't be added
push(arr, {id: 10, name: 'Kyle'}); // will be added

Comments

-1

You can make use of array.filter function in the following way:

let array = [
  { id: 1, name: 'Fabricio' },
  { id: 2, name: 'Leontina' },
  { id: 3, name: 'Rodrigo' }
]

function add (object) {
  if (object) {
    if (array.filter(x => x.id === object.id).length === 0) {
      array.push(object)
    }
  }
}

add({ id: 2, name: 'Evander' }) // won't add
add({ id: 4, name: 'Evander' }) // will add

console.log(array)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.