DEV Community

Cover image for Add Element to Array just if It Doesn't Exist in the Array
Mohamed Mayallo
Mohamed Mayallo

Posted on • Updated on • Originally published at mayallo.com

Add Element to Array just if It Doesn't Exist in the Array

Introduction

In JavaScript, arrays allow duplicating elements and don’t guarantee the uniqueness of their elements.

However, in many cases, we need to push an element into an array just if it didn’t exist beforehand and ignore the process if it already existed.

So, how can we achieve this goal? I think while you landed on this page, you need a quick solution without much stuffing.

So, without further ado, let’s introduce the easiest and the more practical methods.

Set()

JavaScript Set is a collection of unique values. Each value has to occur once in a Set.

If your array’s elements were strings or numbers, Set is the easiest way to achieve your goal.

function addToArrayIfNotExist(val, arr) {
  arr.push(val);

  // Use new Set() to create a new collection, then create a new array from this collection
  const uniqueArr = Array.from(new Set(arr));

  return uniqueArr;
}

console.log(addToArrayIfNotExist(2, ['a', 'b', 'c', 1, 2])); // [ 'a', 'b', 'c', 1, 2 ]
console.log(addToArrayIfNotExist(3, ['a', 'b', 'c', 1, 2])); // [ 'a', 'b', 'c', 1, 2, 3 ]
Enter fullscreen mode Exit fullscreen mode

Includes() Or IndexOf()

These two ways would work fine if your array’s elements were strings or numbers as well.

Firstly, let’s try includes():

function addToArrayIfNotExist(val, arr) {
  const doesAlreadyExist = arr.includes(val);

  // Ignore the process
  if (doesAlreadyExist) return arr;

  // Or push the new value
  arr.push(val);

  return arr;
}

console.log(addToArrayIfNotExist(2, ['a', 'b', 'c', 1, 2])); // [ 'a', 'b', 'c', 1, 2 ]
console.log(addToArrayIfNotExist(3, ['a', 'b', 'c', 1, 2])); // [ 'a', 'b', 'c', 1, 2, 3 ]
Enter fullscreen mode Exit fullscreen mode

Secondly, let’s try indexOf():

function addToArrayIfNotExist(val, arr) {
  const doesAlreadyExist = arr.indexOf(val);

  // Ignore the process (-1 means the element is not exist)
  if (doesAlreadyExist !== -1) return arr;

  // Or push the new value
  arr.push(val);

  return arr;
}

console.log(addToArrayIfNotExist(2, ['a', 'b', 'c', 1, 2])); // [ 'a', 'b', 'c', 1, 2 ]
console.log(addToArrayIfNotExist(3, ['a', 'b', 'c', 1, 2])); // [ 'a', 'b', 'c', 1, 2, 3 ]
Enter fullscreen mode Exit fullscreen mode

Find() Or FindIndex()

That’s great, but what should you do if your array’s elements were objects? The easiest way in such a case is to use either find() or findIndex() methods.

Firstly, let’s try find():

function addToArrayIfNotExist(objVal, arr) {
  // Suppose you check against the object id
  const doesAlreadyExist = arr.find((item) => item.id === objVal.id);

  // Ignore the process
  if (doesAlreadyExist) return arr;

  // Or push the new value
  arr.push(objVal);

  return arr;
}

console.log(addToArrayIfNotExist({ id: 2 }, [{ id: 1 }, { id: 2 }, { id: 3 }])); // [{ id: 1 }, { id: 2 }, { id: 3 }]
console.log(addToArrayIfNotExist({ id: 4 }, [{ id: 1 }, { id: 2 }, { id: 3 }])); // [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]
Enter fullscreen mode Exit fullscreen mode

Secondly, let’s try findIndex():

function addToArrayIfNotExist(objVal, arr) {
  // Suppose you check against the object id
  const doesAlreadyExist = arr.findIndex((item) => item.id === objVal.id);

  // Ignore the process (-1 means the element is not exist)
  if (doesAlreadyExist !== -1) return arr;

  // Or push the new value
  arr.push(objVal);

  return arr;
}

console.log(addToArrayIfNotExist({ id: 2 }, [{ id: 1 }, { id: 2 }, { id: 3 }])); // [{ id: 1 }, { id: 2 }, { id: 3 }]
console.log(addToArrayIfNotExist({ id: 4 }, [{ id: 1 }, { id: 2 }, { id: 3 }])); // [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]

Enter fullscreen mode Exit fullscreen mode

Keep in mind, you can use these methods as well if the array’s elements were strings or numbers.

Conclusion

In this article, we knew how to add an element to an array just if it did not exist in the given array.

Based on the elements types you can choose the proper way to do so:

  1. For numbers or strings elements, you can use new Set(), includes(), or indexOf().
  2. For objects elements, you can use either find() or findIndex().

In fact, there are other ways to achieve that goal, however, I introduced just the easiest and the more practical ways.

Before you leave

If you found this article useful, check out these articles as well:

Top comments (0)