5

I have this array:

[{"name": "Olvier", "id": 123 }, {"name": "Olvier", "id": 124 }]

Now my goal is to prevent adding the same object again to the array:

{"name": "Olvier", "id": 123 }

Is there a Method to do this?

olivier
  • 2,585
  • 6
  • 34
  • 61
  • 2
    Are ids unique? – Jonas Wilms Aug 26 '17 at 12:03
  • You'd have to compare the object, by comparing values of every property to decide whether it is in the array or not. Plain `array.includes` will compare the references. – Nisarg Shah Aug 26 '17 at 12:03
  • What makes you call the inserted object "the same"? Every time you create an object, it is always considered different by JavaScript. If however you have taken an earlier inserted object and want to insert that again (without creating a new object) then they are considered the same. – trincot Aug 26 '17 at 12:08

8 Answers8

6

If your object is created earlier and has the same reference as the one in the array, you can use indexOf:

var myObj = { a: 'b' };
myArray.push(myObj);
var isInArray = myArray.indexOf(myObj) !== -1;

Otherwise you can check it with find:

var isInArray = myArray.find(function(el){ return el.id === '123' }) !== undefined;
Camille Wintz
  • 951
  • 7
  • 8
3

If the id's are unique you can simply check if an object with a certain id exists:

const collection = [
    {"name": "Olvier", "id": 123 },
    {"name": "Olvier", "id": 124 }
];

let person = { "name": "Olvier", "id": 123 };

function addPerson(person) {
    const existingIds = collection.map((addedPerson) => addedPerson.id);

    if (! existingIds.includes(person.id)) {
        collection.push(person);
    }
}

addPerson(person);
JJWesterkamp
  • 7,559
  • 1
  • 22
  • 28
3

You could use Array#some method to determinate that item is already in array or not:

var arr = [
  { name: 'Olvier', id: 123 },
  { name: 'Olvier', id: 124 }
];
var existingItem = arr[1];
var newItem = { name: 'John', id: 125 };
    
if (!arr.some(item => item === existingItem)) {
  arr.push(existingItem);
}
console.log(arr);
    
if (!arr.some(item => item === newItem)) {
  arr.push(newItem);
}
console.log(arr);
alexmac
  • 19,087
  • 7
  • 58
  • 69
1

Recreate the array with Array#reduce and checking with Array#filter

var arr =[{"name": "Olvier", "id": 123 }, {"name": "Olvier", "id": 124 }]

var res = arr.reduce((a,b)=>{
if(a.filter(i=> i.name == b.name).length == 0){
 a.push(b)
}
return a
},[])

console.log(res)
prasanth
  • 22,145
  • 4
  • 29
  • 53
1

You can write custom method to insert new object into array. Before adding new element in the array, first check if the item exist in the array. You can use array#some

var arr = [{"name": "Olvier", "id": 123 }, {"name": "Olvier", "id": 124 }];

var obj1 = {"name": "Olvier", "id": 123 }, obj2 = {"name": "Olvier", "id": 125 };

var insertUniqueObject = function(arr, obj) {
  let isExist = arr.some(o => o.name === obj.name && o.id === obj.id);
  if(!isExist)
    arr.push(obj);
  return arr;
}

console.log(insertUniqueObject(arr, obj1));
console.log(insertUniqueObject(arr, obj2));
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

var myarray = [{"name": "Olvier", "id": 123 }, {"name": "Olvier", "id": 124 }];

var myobj = 
{"name": "Olvier", "id": 123 };

var result = myarray.filter(function (item) {
  return (item.name == myobj.name && item.id == myobj.id);
});

if(result.length==0){
  //add here
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

Probably an id -> object Map is the better datastructure here. You could implement a wrapper for it:

class UserList extends Map {
  constructor(arr){
   super(arr.map(obj => [obj.id,obj]));
  }
  add(obj){
   if(!this.has(obj.id)){
    return this.set(obj.id,obj);
   }
   return false
  }
  remove(obj){
   this.delete(obj.id || obj);
  }
}

var users = new UserList([{"name": "Olvier", "id": 123 }, {"name": "Olvier", "id": 124 }]);

console.log(
  users.add({name:"Jack",id:123}),//false
  users.add({name:"Jack",id:125}),//works
  users.delete(124),//removes Olvier
  users.get(125),//Jack
  [...users.entries()],//a 2d array of [id,obj]
  [...users.values()]//objects only array
);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

A very verbose way of doing it would be sth like:

var IsIncluded = false;
for(var i; i< array.length; i++) {
  if(array[i].name == ObjectToInclude.name && array[i].id == ObjectToInclude.id ) {
    IsIncluded = true;
    break;
  }
}
if(!IsIncluded) {
  array.push(ObjectToInclude);
}
Ente Fetz
  • 443
  • 1
  • 4
  • 10
  • just constructors start with a capital letter by convention. – Jonas Wilms Aug 26 '17 at 12:14
  • Really ? Did not know that. Is there an official convention reference ? – Ente Fetz Aug 26 '17 at 12:15
  • *Most variables and functions should start with a lower case letter. Constructor functions that must be used with the new prefix should start with a capital letter. JavaScript issues neither a compile-time warning nor a run-time warning if a required new is omitted. Bad things can happen if new is not used, so the capitalization convention is the only defense we have. Global variables in browsers should be in all caps.* http://javascript.crockford.com/code.html – Jonas Wilms Aug 26 '17 at 12:30
  • In several years of programming in C, C++, Python, Java, Javascript, HTML, Matlab etc.. I always only used the rule, that functions are lowercase and variables have to start with a capital letter. You are the first one to complain about that. Or is this only specific to Javascript ? – Ente Fetz Aug 26 '17 at 18:13