Languages
[Edit]
EN

JavaScript - copy array with replace item operation

0 points
Created by:
Aaron1
568

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

Quick solution:

// ONLINE-RUNNER:browser;

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

var result = array.map((value, i) => (i === index ? replacement : value));

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

 

Reusable function example

In this example, we create a reusable function that creates a copy of the given array and replaces the item with given index with the replacement.

// ONLINE-RUNNER:browser;

function replaceItem(array, index, replacement) {
    return array.map((value, i) => (i === index ? replacement : value));
}


// Usage example:

var array = [1, 2, 3];

var copy1 = replaceItem(array, 0, 4);
var copy2 = replaceItem(array, 0, 5);

var copy3 = replaceItem(array, 1, 6);
var copy4 = replaceItem(array, 1, 7);

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

console.log(copy3);  // [ 1, 6, 3 ]
console.log(copy4);  // [ 1, 7, 3 ]

 

See also

  1. JavaScript - copy array with append item operation

  2. JavaScript - copy array with prepend item operation

  3. JavaScript - copy array with remove item operation

References

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

Alternative titles

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