Languages
[Edit]
EN

JavaScript - copy array with prepend item operation

0 points
Created by:
Dragontry
731

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

Quick solution:

// ONLINE-RUNNER:browser;

var myArray = [1, 2, 3];
var newItem = 4;

var result = [].concat(newItem, myArray);

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

 

Reusable function example

In this example, we create a reusable function that creates a copy of the given array with an item prepended at the beginning.

// ONLINE-RUNNER:browser;

function prependItem(array, item) {
    return [].concat(item, array);
}


// Usage example:

var array = [1, 2, 3];

var copty1 = prependItem(array, 4);
var copty2 = prependItem(array, 5);
var copty3 = prependItem(array, 6);

console.log(copty1);  // [ 4, 1, 2, 3 ]
console.log(copty2);  // [ 5, 1, 2, 3 ]
console.log(copty3);  // [ 6, 1, 2, 3 ]

 

See also

  1. JavaScript - copy array with append item operation

  2. JavaScript - copy array with replace item operation

  3. JavaScript - copy array with remove item operation

References

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

Alternative titles

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