37

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"];
Ronen Rabinovici
  • 8,680
  • 5
  • 34
  • 46
Hasanuzzaman
  • 558
  • 1
  • 4
  • 11

1 Answers1

61

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

Ronen Rabinovici
  • 8,680
  • 5
  • 34
  • 46
Jahnavi Paliwal
  • 1,721
  • 1
  • 12
  • 20
  • 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!? – Nam G VU Jul 26 '23 at 15:42