Manipulating Arrays

Last Updated on December 11, 2015

forEach()

Pass a callback function that manipulates each element in the referenced array. It sends three arguments along with the function name described below. MDN


arr = [1,"two",3];
arr.forEach(logArrayElements);
// el    = The current element being processed in the array.
// index = The index of the current element being processed in the array.
// array = The array that forEach is being applied to.
function logArrayElements(el, index, array) {
  console.log("The thing in the item " + el);
  console.log("Current item index (from 0) -> " + index);
  console.log("The entire array -> [" + array + "]");
  console.log("----------------");
}

 

shift, unshift, pop, concat, length, join, push


var ani = ["dog", "cat", "rabbit", "deer"];

// .length is not from 0 index but 1
var k = ani.length;
console.log("length -> " + k)
// Output: length -> 4

// .join
var j = ani.join(" and more and ");
console.log("the 'joiner' is the words 'and more and' -> " + j);
// Output: 

// .push adds an index to the end of the array
var k = ani.push("gerbil");
console.log("push -> (added gerbil at end) ");
console.log(ani);
// Output: 

// .unshift adds named thing to 0 index
var l = ani.unshift("giraffe");
console.log("unshift -> (added giraffe at 0) " +  l);
console.log(ani);
// Output: 

// .shift removed first element of array (accepts no params)
console.log("before shift -> " + ani);
var m = ani.shift();
console.log("shifted (removed) -> " + m);
console.log(ani);
// Output: 

// .pop removes last element of array (accepts no params)
console.log("before pop -> " + ani);
var n = ani.pop();
console.log("popped => " + n)
// Output: 

//.concat concatenates arrays
var jim = [1,2,3,4];
var result = ani.concat(jim);
console.log(result);
// Output: