Languages
[Edit]
EN

JavaScript - how to remove element from array by index?

16 points
Created by:
Hayley-Mooney
377

In JavaScript, it is not intuitive at the first time how to remove element by index. Remove 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 amount of the removed elements - we remove 1 element.

 

1. Practical example method example

// ONLINE-RUNNER:browser;

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

// removes 3rd element
var removedElements = array.splice(2, 1); // removed from index: 2, removed elements amount: 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

2. 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 

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