1

I'm trying store the data about users to array in JavaScript. Problem is that i want to add user to array when his ID isn't in that array, yet.

var users = [
  {
    id: 2,
    name: "Kevin"
  },

  {
    id: 1,
    name: "Jason"
  }
];

for(var i = 0; i < users.length; i++){

  if(users[i].id != 1){
    users.push({
      id: 1,
      name: "Adam"
    );
  }

}

It's broken because first user with ID 2 is not equal to 1, but i don't know how to fix it. How it should look:

if(userID isnt in array users){
  // add user to array
}

Can anyone help me with that, please? Thanks.

Hellbyte
  • 53
  • 6
  • [Learn some functional JS](http://reactivex.io/learnrx/). Then this would be trivial. Look into, [`filter`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) or [`find`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/find). – evolutionxbox Apr 03 '18 at 15:00
  • Use the array includes function. https://www.w3schools.com/jsref/jsref_includes_array.asp – Venkat Apr 03 '18 at 15:03

1 Answers1

1

you can use find if the array contains a particular object by var isUserExist = users.find( item => item.id === 3); then add the object

var users = [
  {
    id: 2,
    name: "Kevin"
  },

  {
    id: 1,
    name: "Jason"
  }
];
var isUserExist = users.find( item => item.id === 3);
if(!isUserExist){
  users.push({
      id: 3,
      name: "Adam"
    });
}
console.table(users);
Saravanan I
  • 1,229
  • 6
  • 9