How to remove element from an array in JavaScript?

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

I want to remove the 1st element of the array so that it becomes:

var arr = [2,3,5,6];

To extend this question, what if I want to remove the 2nd element of the array so that it becomes:

var arr = [1,3,5,6];

Answers:

Answer

For a more flexible solution, use the splice() function. It allows you to remove any item in an Array based on Index Value:

var indexToRemove = 0;
var numberToRemove = 1;

arr.splice(indexToRemove, numberToRemove);
Answer

The Array.prototype.shift method removes the first element from an array, and returns it. It modifies the original array.

var a = [1,2,3]
// [1,2,3]
a.shift()
// 1
a
//[2,3]
Answer
arr.slice(begin[,end])

is non destructive, splice and shift will modify your original array

Answer

Wrote a small article about inserting and deleting elements at arbitrary positions in Javascript Arrays.

Here's the small snippet to remove an element from any position. This extends the Array class in Javascript and adds the remove(index) method.

// Remove element at the given index
Array.prototype.remove = function(index) {
    this.splice(index, 1);
}

So to remove the first item in your example, call arr.remove():

var arr = [1,2,3,5,6];
arr.remove(0);

To remove the second item,

arr.remove(1);

Here's a tiny article with insert and delete methods for Array class.

Essentially this is no different than the other answers using splice, but the name splice is non-intuitive, and if you have that call all across your application, it just makes the code harder to read.

Answer

Others answers are great, I just wanted to add an alternative solution with ES6 Array function : filter.

filter() creates a new array with elements that fall under a given criteria from an existing array.

So you can easily use it to remove items that not pass the criteria. Benefits of this function is that you can use it on complex array not just string and number.

Some examples :

Remove first element :

// Not very useful but it works
function removeFirst(element, index) {
  return index > 0;
}
var arr = [1,2,3,5,6].filter(removeFirst); // [2,3,4,5,6]

Remove second element :

function removeSecond(element, index) {
  return index != 1;
}
var arr = [1,2,3,5,6].filter(removeSecond); // [1,3,4,5,6]

Remove odd element :

function removeOdd(element, index) {
  return !(element % 2);
}
var arr = [1,2,3,5,6].filter(removeOdd); [2,4,6]

Remove items not in stock

const inventory = [
  {name: 'Apple', qty: 2},
  {name: 'Banana', qty: 0},
  {name: 'Orange', qty: 5}
];

const res = inventory.find( product => product.qty > 0);


Answer

You can use the ES6 Destructuring Assignment feature with a rest operator. A comma indicates where you want to remove the element and the rest (...arr) operator to give you the remaining elements of the array.

const source = [1,2,3,5,6];

function removeFirst(list) {
   var  [, ...arr] = list;
   return arr;
}
const arr = removeFirst(source);
console.log(arr); // [2, 3, 5, 6]
console.log(source); // [1, 2, 3, 5, 6]

Answer

Array.splice() has the interesting property that one cannot use it to remove the first element. So, we need to resort to

function removeAnElement( array, index ) {
    index--;

    if ( index === -1 ) {
        return array.shift();
    } else {
        return array.splice( index, 1 );
    }
}
Answer

shift() is ideal for your situation. shift() removes the first element from an array and returns that element. This method changes the length of the array.

array = [1, 2, 3, 4, 5];

array.shift(); // 1

array // [2, 3, 4, 5]
Answer

Maybe something like this:

arr=arr.slice(1);
Answer

You can also do this with reduce:

let arr = [1, 2, 3]

arr.reduce((xs, x, index) => {
        if (index == 0) {
            return xs
        } else {
            return xs.concat(x)
        }
    }, Array())

// Or if you like a oneliner
arr.reduce((xs, x, index) => index == 0 ? xs : xs.concat(x), Array())
Answer

Typescript solution that does not mutate original array

function removeElementAtIndex<T>(input: T[], index: number) {
  return input.slice(0, index).concat(input.slice(index + 1));
}
Answer

There are multiple ways to remove an element from an Array. Let me point out most used options below. I'm writing this answer because I couldn't find a proper reason as to what to use from all of these options. The answer to the question is option 3 (Splice()).

1) SHIFT() - Remove First Element from Original Array and Return the First Element

See reference for Array.prototype.shift(). Use this only if you want to remove the first element, and only if you are okay with changing the original array.

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

2) SLICE() - Returns a Copy of the Array, Separated by a Begin Index and an End Index

See reference for Array.prototype.slice(). You cannot remove a specific element from this option. You can take only slice the existing array and get a continuous portion of the array. It's like cutting the array from the indexes you specify. The original array does not get affected.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

3) SPLICE() - Change Contents of Array by Removing or Replacing Elements at Specific Indexes.

See reference for Array.prototype.splice(). The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Returns updated array. Original array gets updated.

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.