Languages
[Edit]
EN

JavaScript - copy array with remove item operation

0 points
Created by:
sienko
743

In this article, we would like to show you how to copy an array with removed item using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

var array = [1, 2, 3, 4];
var index = 1;

var result = array.filter((value, i) => i !== index);

console.log(result);  // [ 1, 3, 4 ]

 

Reusable function example

In this example, we create a reusable function that creates a copy of a given array with an item removed by the index.

// ONLINE-RUNNER:browser;

function removeItem(array, index) {
    return array.filter((value, i) => i !== index);
}


// Usage example:

var array = [1, 2, 3, 4];

var copy1 = removeItem(array, 0);
var copy2 = removeItem(array, 1);
var copy3 = removeItem(array, 2);

console.log(copy1);  // [ 2, 3, 4 ]
console.log(copy2);  // [ 1, 3, 4 ]
console.log(copy3);  // [ 1, 2, 4 ]

 

See also

  1. JavaScript - copy array with append item operation

  2. JavaScript - copy array with prepend item operation

  3. JavaScript - copy array with replace item operation

References

  1. Array.prototype.filter() - JavaScript | MDN

Alternative titles

  1. JavaScript - copy array with removed item
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