Let´s say I have this array:
let array = ["somevalue", "anothervalue"]
So what I wanted to da was to add a value, for example:
let foo = {bar: true}
and add this value at index 0, but not overwrite the old value, rather kind of 'push' the rest of the values back. I´ve heard of array = [foo, ...array]
but I am not quite sure what it does and how and when to use it.
Anyone any ideas?
CodePudding user response:
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
CodePudding user response:
It simply append the foo in front of array. so array will become
[{bar: true}, "somevalue", "anothervalue"]
Alternate :
You can also use unshift, it also append data at index 0, eg.
let array = [2, 3, 4]
array.unshift(1)
console.log(array) /// output : [1, 2, 3, 4]