user198729
user198729

Reputation: 63626

How to remove element from an array in JavaScript?

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

Remove the first element

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

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

Remove the second element

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

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

Upvotes: 421

Views: 456980

Answers (13)

Martin Choraine
Martin Choraine

Reputation: 2431

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 elements:

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.filter(product => product.qty > 0);

Upvotes: 12

The Jared Wilcurt
The Jared Wilcurt

Reputation: 340

2024 answer - Use .toSpliced()

Since mid-2023 arr.toSpliced() has had wide support. You can use it in chains, like so:

[4, 5, 2, 1, 3]
  // [1, 2, 3, 4, 5]
  .toSorted()
  // [10, 20, 30, 40, 50]
  .map((x) => x * 10)
  // [10, 30, 40, 50]
  .toSpliced(1, 1)
  // [10, 30, 40]
  .filter((x) => x < 45)
  // '10_30_40'
  .join('_');

To remove the first item in an array:

const myArray = ['a', 'b', 'c', 'd'];
const indexToStartRemovingFrom = 0;
const amountOfItemsToRemove = 1;
const newArray = myArray.toSpliced(indexToStartRemovingFrom, amountOfItemsToRemove);

console.log({ myArray, newArray });
// { myArray: ['a', 'b', 'c', 'd'], newArray: ['b', 'c', 'd'] }

Upvotes: 0

Gabriel McAdams
Gabriel McAdams

Reputation: 58251

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);

Upvotes: 450

Keet Sugathadasa
Keet Sugathadasa

Reputation: 13502

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"]

Upvotes: 9

Adam Pietrasiak
Adam Pietrasiak

Reputation: 13184

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));
}

Upvotes: 2

user11534547
user11534547

Reputation:

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())

Upvotes: -1

Brendan
Brendan

Reputation: 1496

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]

Upvotes: 3

p3drosola
p3drosola

Reputation: 5877

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]

Upvotes: 62

Gabriel Schulhof
Gabriel Schulhof

Reputation: 13

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 );
    }
}

Upvotes: -2

JP Silvashy
JP Silvashy

Reputation: 48495

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]

Upvotes: 717

ThatGuyYouKnow
ThatGuyYouKnow

Reputation: 460

Maybe something like this:

arr=arr.slice(1);

Upvotes: 21

kiuma
kiuma

Reputation: 901

arr.slice(begin[,end])

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

Upvotes: 76

Anurag
Anurag

Reputation: 141859

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.

Upvotes: 18

Related Questions