How can I add new array elements at the beginning of an array in JavaScript?
Use unshift
. It's like push
, except it adds elements to the beginning of the array instead of the end.
unshift
/push
- add an element to the beginning/end of an arrayshift
/pop
- remove and return the first/last element of an array
A simple diagram...
unshift -> [array] <- push
shift <- [array] -> pop
and chart:
add remove start end
push X X
pop X X
unshift X X
shift X X
Check out the MDN Array documentation. Virtually every language that has the ability to push/pop elements from an array will also have the ability to unshift/shift (sometimes called push_front
/pop_front
) elements, you should never have to implement these yourself.
As pointed out in the comments, if you want to avoid mutating your original array, you can use concat
, which concatenates two or more arrays together. You can use this to functionally push a single element onto the front or back of an existing array; to do so, you need to turn the new element into a single element array:
const array = [3, 2, 1]
const newFirstElement = 4
const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]
console.log(newArray);
js: add element at the start of an array
Ok,
let arr = [1,2]
let foo={bar:true}
arr=[foo].concat(arr)
also what you already know works
arr=[foo, ...arr]
That's it
How to insert an item into an array at a specific index (JavaScript)
You want the splice
function on the native array object.
arr.splice(index, 0, item);
will insert item
into arr
at the specified index
(deleting 0
items first, that is, it's just an insert).
In this example we will create an array and add an element to it into index 2:
var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";
console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge
arr.splice(2, 0, "Lene");
console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge
Copy array items into another array
Use the concat function, like so:
var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);
The value of newArray
will be [1, 2, 3, 4]
(arrayA
and arrayB
remain unchanged; concat
creates and returns a new array for the result).
javascript pushing element at the beginning of an array
Use unshift
, which modifies the existing array by adding the arguments to the beginning:
TheArray.unshift(TheNewObject);
How to append something to an array?
Use the Array.prototype.push
method to append values to the end of an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);
How to append new array to beginning of multi-dimensional array
Here you go with the solution https://jsfiddle.net/fkz9ubug/
var vArr = [[1, 1], [2, 3], [3, 3]];var newv = [4, 4];vArr.unshift(newv)
console.log(vArr);
How to extend an existing JavaScript array with another array, without creating a new array
The .push
method can take multiple arguments. You can use the spread operator to pass all the elements of the second array as arguments to .push
:
>>> a.push(...b)
If your browser does not support ECMAScript 6, you can use .apply
instead:
>>> a.push.apply(a, b)
Or perhaps, if you think it's clearer:
>>> Array.prototype.push.apply(a,b)
Please note that all these solutions will fail with a stack overflow error if array b
is too long (trouble starts at about 100,000 elements, depending on the browser).
If you cannot guarantee that b
is short enough, you should use a standard loop-based technique described in the other answer.
Adding text to beginning of each array element
for(var i=0;i<array.length;i++){
array[i]="#"+array[i];
}
Related Topics
Array.Fill(Array) Creates Copies by References Not by Value
How to Check If Dst (Daylight Saving Time) Is in Effect, and If So, the Offset
Why Shouldn't Jsx Props Use Arrow Functions or Bind
How to Iterate Through Table Rows and Cells in JavaScript
Asynchronous for Cycle in JavaScript
Call Static Methods from Regular Es6 Class Methods
When Should I Use Jquery's Document.Ready Function
Logical Operators in JavaScript - How to Use Them
Multi-Row Insert with Pg-Promise
Trying to Fire the Onload Event on Script Tag
Why Are Callbacks from Promise '.Then' Methods an Anti-Pattern
How to Cancel an Http Fetch() Request
JavaScript Regex Multiline Text Between Two Tags
How to Filter Multiple Values (Or Operation) in Angularjs
How to Send JSON Instead of a Query String with $.Ajax