43

How to remove an array's element by its index?

For example

fruits = ["mango","apple","pine","berry"];

Remove element fruits[2] to get

fruits = ["mango","apple","berry"];
0

1 Answer 1

71

You can use splice as: array.splice(start_index, no_of_elements_to_remove). Here's the solution to your example:

const fruits = ["mango","apple","pine","berry"]; 
const removed = fruits.splice(2, 1); // Mutates fruits and returns array of removed items
console.log('fruits', fruits); // ["mango","apple","berry"]
console.log('removed', removed); // ["pine"]

This will remove one element from index 2, i.e. after the operation fruits=["mango","apple","berry"];

Sign up to request clarification or add additional context in comments.

1 Comment

No idea why slice(i,j) in nodejs is get sub array from index i to j-1, and NOT remove at index i with j items!?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.