Demonstrate array manipulation methods in JavaScript

by Michael Prosser

JavaScript

/*

I Put together a little script to go over array manipulation

methods that you should know:

push() - add to end of array
unshift() - add to beginning of array
pop() - remove last item
shift() - remove first item

splice() - removes a specific item(s) from array
indexOf() - returns the index of the item matching 

We start out with a static array with 4 items

*/

let items = [
  "Book Shelf",
  "Coffee Table",
  "Sofa",
  "Lamp"
];

/*

if we want to add an element to an array it is usually added 
to the end of the array using push()

let's add an item..

*/

items.push("Rug");

/*

our array now looks like this:

["Book Shelf", "Coffee Table", "Sofa", "Lamp", "Rug"]

if we output it in the console

*/

console.log(items);

/*

You can also add an element to the beginning of an array using unshift()

This is not a very common thing with our coding model

*/

items.unshift("Painting");

console.log(items);

/*

we now have 

["Painting", "Book Shelf", "Coffee Table", "Sofa", "Lamp", "Rug"]

You can call pop() to remove the last item in an array or 
shift() to remove the first
but what about if we want to remove the "Book Shelf"?

You would use splice()

This is something you should learn because it is used a lot, here is an
example:

items.splice( indexToStartOn, numberOfItemsToDelete );

the first paramater is 0 based because it is an index so we know that 
we want to remove the second item in our new array of:

["Painting", "Book Shelf", "Coffee Table", "Sofa", "Lamp", "Rug"]

We would do that with this:

*/

items.splice(1,1);

console.log(items);

/*

probably something that is n ot so obvious when starting with arrays 
is using indexOf()

How this works is the paramteter is the item you are check the array for:

items.indexOf("Book Worm");

But notice if I output the value in the console it gives me -1

*/

console.log(items.indexOf("Book...