remove elements from an array in javascript

To remove elements from an array in JavaScript, you have several options. You can use the splice() method, the slice() method, or the pop() method.

splice()

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. The first argument of splice() specifies the starting index from which to remove elements. The second argument specifies the number of elements to remove. Additional arguments can be provided to add new elements in place of those that were removed.

index.tsx
let arr = [1, 2, 3, 4, 5];
arr.splice(2, 1); // remove one element starting from index 2
console.log(arr); // [1, 2, 4, 5]
123 chars
4 lines

slice()

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

index.tsx
let arr = [1, 2, 3, 4, 5];
let newArr = arr.slice(0, 2).concat(arr.slice(3)); // remove element at index 2
console.log(newArr); // [1, 2, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
181 chars
5 lines

pop()

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

index.tsx
let arr = [1, 2, 3, 4, 5];
arr.pop(); // remove the last element
console.log(arr); // [1, 2, 3, 4]
99 chars
4 lines

gistlibby LogSnag