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);


No comments:

Post a Comment

Your feedback is always appreciated. I will try to reply to your queries as soon as time allows.Please don't spam,spam comments will be deleted upon reviews.