Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

js push if not exists

// ✅ With primitives
const arr1 = ['a', 'b', 'c', 'd'];
const value1 = 'e';

if (!arr1.includes(value1)) {
  arr1.push(value1);
}

// ✅ With Objects
const arr2 = [{id: 1}, {id: 2}];
const value2 = {id: 3};

const index = arr2.findIndex(object => object.id === value2.id);

if (index === -1) {
  arr2.push(value2);
}
Source by bobbyhadz.com #
 
PREVIOUS NEXT
Tagged: #js #push #exists
ADD COMMENT
Topic
Name
2+3 =