append to start of array in javascript

To append an element to the start of an array in JavaScript, you can use the unshift() method. This method is used to add one or more elements at the beginning of an array and returns the new length of the array.

Example:

index.tsx
let arr = [2, 3, 4];
arr.unshift(1);

console.log(arr); // Output: [1, 2, 3, 4]
80 chars
5 lines

If you want to append multiple elements at once, you can pass them as separate arguments to the unshift() method. For example:

index.tsx
let arr = [2, 3, 4];
arr.unshift(0, 1);

console.log(arr); // Output: [0, 1, 2, 3, 4]
86 chars
5 lines

Alternatively, you can use the spread operator (...) to prepend one or more elements to an array. This method creates a new array by concatenating the values passed as arguments to the existing array.

Example:

index.tsx
let arr = [2, 3, 4];
arr = [1, ...arr];

console.log(arr); // Output: [1, 2, 3, 4]
83 chars
5 lines

Using this method, you can even append multiple elements to the beginning of an array:

index.tsx
let arr = [2, 3, 4];
arr = [0, 1, ...arr];

console.log(arr); // Output: [0, 1, 2, 3, 4]
89 chars
5 lines

gistlibby LogSnag