How to Remove Elements from an Array in JavaScript

Updated: February 19, 2023 By: Frienzied Flame Post a comment

As a programmer, there might be scenarios where you have to remove specific elements from an array in Javascript. It is important to understand the various techniques available for doing so in order to select the most efficient and appropriate one for the task at hand. In this article, I will be discussing the best strategies for removing specific elements from arrays in Javascript.

Using the splice() Method

The splice() method is a powerful tool for the task since it is capable to remove a single or a range of elements from an array.

The syntax for the splice method is as follows:

removedElements = array.splice(startIndex, deleteCount);

Where:

  • startIndex: The position to start removing elements
  • deleteCount: The number of elements that you want to delete
  • removedElements: The splice() method returns the removed elements

For instance, if you wanted to remove the third, fourth, and fifth elements from an array called myArray, you could use the following code:

myArray.splice(2, 3);

Let’s see the practical example below for more clarity:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const removed = numbers.splice(2, 5);

console.log(removed); // [3, 4, 5, 6, 7]
console.log(numbers); // [1, 2, 8, 9, 10]

Using the filter() Method

The filter() method is a powerful tool for removing specific elements from an array based on a given condition. It takes a callback function as an argument and returns a new array with all of the elements that pass the given test.

For example, if you wanted to remove all of the elements from an array called myArray that are greater than 10, you could use the following code:

let filteredArray = myArray.filter(num => num = 10);

A new array is created and returned by the filter() method while the original array is intact. The example below demonstrates how to remove all strings whose length is less than 6 from a given array of words:

const words = [
  'spray',
  'limit',
  'elite',
  'exuberant',
  'destruction',
  'present',
];
const result = words.filter((word) => word.length >= 6);
console.log(result);

Output:

[ 'exuberant', 'destruction', 'present' ]

Using the reduce() Method

The reduce() method gives us another solution to remove elements from an array. The example below depicts how to make use of the reduce() method to eliminate all numbers that are less than 10 from a given array. Only those which are equal to or greater than 10 will be kept.

const myArray = [1, 5, 6, 7, 8, 9, 10, 11, 20, 30, 33];
let reducedArray = myArray.reduce((acc, num) => {
  if (num >= 10) {
    acc.push(num);
  }
  return acc;
}, []);

console.log(reducedArray);

Output:

[ 10, 11, 20, 30, 33 ]

Using the map() Method

The map() method brings to the table another approach to removing elements from a given array.

Example

Let’s say we have an array of objects where each object contains information about a person, including name and age. Our goal is to get an array containing people who can drive (assuming that over 18 is the condition). Here’s the code:

const people = [
    { name: 'Wes', age: 24 },
    { name: 'Kait', age: 32 },
    { name: 'Irv', age: 9 },
    { name: 'Lux', age: 7 }
];

const whoCanDrive = people.filter(person => person.age >= 18);
console.log(whoCanDrive);

Output:

[ { name: 'Wes', age: 24 }, { name: 'Kait', age: 32 } ]

Like the filter() and the reduce() methods, The map() method is a great way to quickly remove specific elements from an array based on a given condition.

Using the Pop() and Shift() Methods

The pop() and shift() methods are two of the most basic and straightforward ways to remove elements from an array. The pop() method removes the last element from the array, while the shift() method removes the first element from the array. Both of these methods make changes to the original array and return the element that was removed, so they can be used to store the removed elements in a variable.

Example:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const removedElement = arr.pop();
console.log('Array: ', arr);
console.log('Removed Element: ', removedElement);

Output:

Array:  [
  1, 2, 3, 4, 5,
  6, 7, 8, 9
]
Removed Element:  10

Another example:

const arr = ['a', 'b', 'c', 'd', 'e'];

const removedElement = arr.shift();
console.log('Array: ', arr);
console.log('Removed Element: ', removedElement);

Output:

Array:  [ 'b', 'c', 'd', 'e' ]
Removed Element:  a

Limitations: These methods have huge disadvantages and are less flexible because they cannot remove an element if it is not at the beginning or end of the given array.

Using for Loop

Using the for loop is the traditional way to remove some elements from an array. It takes a starting index, an ending index, and a step size as arguments, and it executes the given code for each element in the array. In the case of removing elements from an array, the given code can be used to identify and remove the elements that you want to remove.

Example

The code snippet below eliminates all odd numbers and gives you an array that contains only even numbers:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = [];
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    evenNumbers.push(numbers[i]);
  }
}

console.log(evenNumbers);

Output:

[ 2, 4, 6, 8, 10 ]

Define a custom function

If you need to remove elements from an array that don’t fit neatly into any of the other strategies discussed in this article, you can always define a custom function to do the job.

Here is our custom function (in some cases, you need to tweak it a bit):

const removeElements = (arr, unwantedElements) => {
  let newArray = [];
  arr.forEach((e) => {
    if (unwantedElements.indexOf(e) === -1) {
      newArray.push(e);
    }
  });
  return newArray;
};

This function can take 2 arguments:

  • arr: The input array
  • unwantedElements: An array that contains elements you want to get rid of

Let’s give our removeElements() function a try:

const words = ["hello", "world", "lighthouse", "darkhouse"];
console.log(removeElements(words, ["lighthouse", "darkhouse]));

Output:

[ 'hello', 'world' ]

Conclusion

I hope that this article has provided you with a better understanding of the various methods available for removing elements from arrays in Javascript. With this knowledge, you should be better equipped to make the right choice when the time comes.

Any questions related to the topic of the article will also be appreciated. We’ll be more than happy if you write down your comment. Good lucks and have a nice day!