Languages
[Edit]
EN

JavaScript - remove element from array by index

16 points
Created by:
Hayley-Mooney
677

In JavaScript, it is not intuitive the first time how to remove elements by index. Removing the element by index operation can be achieved with Array.prototype.splice method. This article is focused on how to do it.

Quick solution:

array.splice(index, 1);  // removes 1 element

Where:

  • array - from this array, we want to remove an element,
  • index - removed element index,
  • 1 - means the number of removed elements.

 

Practical example

// ONLINE-RUNNER:browser;

//  index:    0    1    2    3
var array = ['a', 'b', 'c', 'd'];

var removedElements = array.splice(2, 1);  // removes only 3rd element (index: 2, count: 1)

console.log(array);
console.log(removedElements);

Array.prototype.splice(index, count) method:

  • takes:
    • index - starting from this index elements will be removed,
    • count - number of the elemnts to remove starting from index,
  • returns:
    • array with removed elements
  • warning:
    • splice() method middifies array

Reusable function

// ONLINE-RUNNER:browser;

const removeItem = (array, index) => {
    const items = array.splice(index, 1);
    if (items.length > 0) {
        return items[0];
    }
    return null;
};


// Usage example:

//    index:    0    1    2    3
const array = ['a', 'b', 'c', 'd'];

const removedItem = removeItem(array, 2);

console.log(array);
console.log(removedItem);

 

References

  1. Array.prototype.splice method - MDN Docs 

Alternative titles

  1. JavaScript - how to remove element from array by index?
  2. JavaScript - remove element at position from array
  3. JavaScript - how to remove element at position from array?
  4. JavaScript - delete element from array by index
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join