Categories
JavaScript Answers

How to Prepend Values to a JavaScript Array?

Spread the love

Sometimes, we may want to prepend values to a JavaScript array.

In this article, we’ll look at how to prepend values to a JavaScript array.

Array.prototype.unshift

We can use the unshift method to prepend one or more items to an array.

For instance, we can write:

const a = [1, 2, 3, 4];
a.unshift(0);
console.log(a)

unshift prepends an item in place, so we get:

[0, 1, 2, 3, 4]

as the new value of a .

We can pass in as many values as we want, so we can write:

const a = [1, 2, 3, 4];
a.unshift(-1, 0);
console.log(a)

Then we get:

[-1, 0, 1, 2, 3, 4]

as the value of a .

We can also spread an array’s value as arguments of unshift .

For instance, we can write:

const a = [1, 2, 3, 4];
const b = [-1, 0]
a.unshift(...b);
console.log(a)

Then we get the same result as the previous example since we spread the entries of b as arguments of unshift .

Using the Spread Operator

We can also use the spread operator to prepend values to an array.

This will return a new array instead of pretending items in place to an existing array.

For instance, we can write:

const a = [1, 2, 3, 4];
const b = [-1, 0]
const c = [...b, ...a]
console.log(c)

We create the c variable and assign it an array with the values of b spread into the new array first.

Then we spread the entries of a into the same array next.

So c is:

[-1, 0, 1, 2, 3, 4]

as a result.

Array.prototype.concat

Another array method we can use to prepend items to an array is to use the concat method.

It also returns a new array instead of prepending items in-place.

For instance, we can write:

const a = [1, 2, 3, 4];
const b = [-1, 0]
const c = b.concat(a)
console.log(c)

to call concat on b with the array a .

This lets us add the entries from a after the entries of b in the returned array.

So c is [-1, 0, 1, 2, 3, 4] as a result.

Conclusion

We can use various array methods or the spread operator to prepend entries into an array.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.