HOW DO YOU ADD AN ELEMENT AT THE BEGINING OF AN ARRAY? HOW DO YOU ADD ONE AT THE END?

How do you add an element at the begining of an array? How do you add one at the end?

var myArray = [‘a’, ‘b’, ‘c’, ‘d’];
myArray.push(‘end’);
myArray.unshift(‘start’);
console.log(myArray); // [“start”, “a”, “b”, “c”, “d”, “end”]
With ES6, one can use the spread operator:

myArray = [‘start’, …myArray];
myArray = […myArray, ‘end’];
Or, in short:

myArray = [‘start’, …myArray, ‘end’];

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>