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?
            Asked
            
        
        
            Active
            
        
            Viewed 4,949 times
        
    0
            
            
        
        Jonas
        
- 52
 - 1
 - 8
 
3 Answers
3
            
            
        let array = ["somevalue", "anothervalue"]
let foo = {bar: true}
array.unshift(foo);
console.log(array); // prints [{bar: true}, "somevalue", "anothervalue"]
Similarly, the shift() method removes the first item in the array.
1
            
            
        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]
        Abhishek Yadav
        
- 23
 - 4
 
0
            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
        Punisher
        
- 30
 - 6