Friday, May 12, 2023

Push into an Array in JavaScript


let myarray = [1,2,3,4,5]


// Add to the start of an array

Array.unshift(element);

myarray.unshift(100); // output 100,1,2,3,4,5


// Add to the end of an array

Array.push(element);

myarray.push(100); // output 1,2,3,4,5,100



// Add to a specified location

Array.splice(start_position, 0, new_element...);

myarray.splice(2, 0, 100,200); // output 1,2,100,200,3,4,5



// Add with concat method without mutating original array

let newArray = [].concat(element);

let newmyarray = myarray.concat(10,20);