How to remove elements from array in JavaScript

how-to-remove-elements-from-array-in-javascript

In JavaScript, there are several ways to remove elements from an array, each with its own advantages and disadvantages.

  • Using shift(), pop() to remove first or last element.
  • Using filter() to filter elements conditionally.
  • Using splice() to add, replace, and remove elements at any positions.
  • Using length data property to remove elements beyond smaller new length.

It’s generally recommended to use the splice() or filter() method to remove elements from an array, as they are efficient and provide a simple and effective way to remove elements based on a specific condition.

Using the pop() method

This method removes the last element from an array and returns it, if the array is empty, it returns undefined. It’s also worth noting that this method modifies the original array, so if you don’t want to modify the array, you should make a copy before calling.

const arr = [1, 2, 3, 4];
const lastElement = arr.pop();

console.log(arr); // [1, 2, 3]
console.log(lastElement); // 4

Using the shift() method

This method modifies the original array by removing the first element and returns that removed element. If the array is empty, it returns undefined.

const arr = [1, 2, 3, 4];
const firstElement = arr.shift();

console.log(arr); // [2, 3, 4]
console.log(firstElement); // 1

This method can be useful when you need to process elements in an array in a specific order, such as a queue or a first-in, first-out (FIFO) data structure. However, keep in mind that removing elements from the beginning of an array can be less efficient than removing elements from the end of an array, because all remaining elements need to be shifted down by one index.

Using the splice() method

This is a powerful method that allows you to modify an array in various ways. However, it can also be a bit tricky to use, especially if you’re not familiar with its arguments and how they work together.

This method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. It overwrites the original array and returns an array containing the removed elements.

var arr = [1, 2, 3, 4, 5];

// add 6 and 7 at the end of the array
arr.splice (arr.length, 0, 6, 7); // returns []
console.log (arr); // [1, 2, 3, 4, 5, 6, 7]

// remove the first element of the array
arr.splice (0, 1); // returns [1]
console.log (arr); // [2, 3, 4, 5, 6, 7]

// replace the third and fourth elements with "a" and "b"
arr.splice (2, 2, "a", "b"); // returns [4, 5]
console.log (arr); // [2, 3, "a", "b", 6, 7]

// remove 6 from the array
arr.splice (4, 1); // returns [6]
console.log (arr); // [2, 3, "a", "b", 7]

Using the filter() method

This method allows you to filter an array and return a new array with only the elements that meet a certain criteria. You can use the filter() method to remove elements from an array based on a certain condition.

const arr = [1, 2, 3, 4];
const filteredArr = arr.filter(number => number % 2 !== 0);

console.log(filteredArr); // [1, 3]

Note that the filter() method does not modify the original array, but creates a new array. If you want to remove the elements from the original array, you can assign the result of filter() back to the original array:

const arr = [1, 2, 3, 4, 5];
arr = arr.filter(element => element !== 3);
console.log(arr); // output: [1, 2, 4, 5]

Using the slice() method

This method can be used to extract a portion of an array, and can effectively be used to remove elements from an array. You can use slice() to extract all the elements before or after the element you want to remove, and concatenate them to form a new array without the removed element.

const arr = [1, 2, 3, 4, 5];
const index = 2;
const newArr = arr.slice(0, index).concat(arr.slice(index + 1));
console.log(newArr); // [1, 2, 4, 5]

Using length data property

The length data property of an Array instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

Setting length to a value smaller than the current length truncates the array — elements beyond the new length are deleted.

let arr = [1, 2, 3, 4, 5];
console.log(arr.length); // 5

arr.length = 3; // set the length to 3, removing the last two elements
console.log(arr); // [1, 2, 3]

arr.length = 0; // set the length to 0, removing all elements
console.log(arr); // []

When length is set to a bigger value than the current length, the array is extended by adding empty slots, not actual undefined values. Setting length to an invalid value (e.g. a negative number or a non-integer) throws a RangeError exception.

Using the delete operator

The delete operator in JavaScript can be used to remove a property from an object, but it’s not recommended to use it to remove an element from an array. Here’s an example of how to use delete to remove a property from an object:

const obj = {a: 1, b: 2, c: 3};
delete obj.b;
console.log(obj); // output: {a: 1, c: 3}

However, when you use delete to remove an element from an array, the array’s length won’t be updated, and creates a sparse array with an empty slots, which are not the same as slots filled with the value undefined. Here’s an example:

const arr = [1, 2, 3];
delete arr[1];
console.log(arr); // [ 1, <1 empty item>, 3 ]

In some operations, empty slots behave as if they are filled with undefined. But in others (most notably array iteration methods), empty slots are skipped.

Therefore, it’s generally recommended to use the splice() method to remove elements from an array, rather than using the delete operator. The splice() method updates the array’s length and removes the element completely.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
machine-learning-communities:-q1-‘23-highlights-and-achievements

Machine Learning Communities: Q1 ‘23 highlights and achievements

Next Post
introduction-to-gee,-climate-engine,-and-satellite-data

Introduction to GEE, CLIMATE Engine, and Satellite Data

Related Posts