Languages
[Edit]
EN

JavaScript - array push() if element doesn't exist in array

0 points
Created by:
Frida-Timms
667

In this article, we would like to show you how to push an element into an array if doesn't exist using JavaScript.

Quick solution for primitive values:

// ONLINE-RUNNER:browser;

const array = ['a', 'b', 'c'];
const value = 'd';

if (!array.includes(value)) {
    array.push(value);
}

console.log(array); // [ 'a', 'b', 'c', 'd' ]

 

1. Compare objects by property

In this example, we compare objects by a single property - id using findIndex() method. If the object with such id doesn't already exist it will be added using push() method.

// ONLINE-RUNNER:browser;

const array = [{ id: 1 }, { id: 2 }];
const value = { id: 3 };

const index = array.findIndex((object) => object.id === value.id);

if (index === -1) {
    array.push(value);
}

console.log(JSON.stringify(array, null, 4)); // [ { id: 1 }, { id: 2 }, { id: 3 } ]

Note:

The findIndex() method returns -1 if no element passes the provided test.

2. Compare multiple object properties

In this example, we create pushIfNotExist() function that uses compare() function to push an object into an myArray if it doesn't already exist. The compare() checks if an object exists in the array by executing the comparator function on every element in array.

// ONLINE-RUNNER:browser;

const compare = (array, comparator) => {
    for (let i = 0; i < array.length; ++i) {
        if (comparator(array[i])) return true;
    }
    return false;
};

const pushIfNotExist = (array, element, comparator) => {
    if (!compare(array, comparator)) {
        array.push(element);
    }
};


// Usage example:

const myArray = [{ id: 1, name: 'Kate' }];

const object1 = { id: 1, name: 'Kate' }; // already exists
const object2 = { id: 2, name: 'Tom' };  // doesn't exist

pushIfNotExist(myArray, object1, (obj) => obj.id === object1.id && obj.name === object1.name);
pushIfNotExist(myArray, object2, (obj) => obj.id === object2.id && obj.name === object2.name);

console.log(JSON.stringify(myArray, null, 4)); // [ { id: 1, name: 'Kate' }, { id: 2, name: 'Tom' } ]

 

References

  1. Array.prototype.push() - JavaScript | MDN
  2. Array.prototype.includes() - JavaScript | MDN
  3. Array.prototype.findIndex() - JavaScript | MDN

Alternative titles

  1. JavaScript - array push() if element does not exist in array
  2. JavaScript - push element into array if doesn't exist
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join