Editing Arrays

Last Updated on December 15, 2015

Array manipulation: shift, unshift, pop, concat, length, join, push


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

.length is not from 0 index but 1


var i = ani.length;
console.log("length -> " + i)
// OUTPUT: length -> 4

.join – the ‘joiner’ adds words between items


var j = ani.join(" and cock and ");
console.log("the 'joiner' is the words 'and cock and' -> " + j)
// OUTPUT: dog and cock and cat and cock and rabbit and cock and deer

There is no joiner after the last item.

.push adds an index to the end of the array


var k = ani.push("gerbil"); // Adds gerbil to end.
console.log(ani);
// OUTPUT: ["dog", "cat", "rabbit", "deer", "gerbil"]

.unshift adds named thing to 0 index


var l = ani.unshift("giraffe");
console.log("unshift -> (added giraffe at 0) " +  l);
console.log(ani);
// OUTPUT: ["giraffe", "dog", "cat", "rabbit", "deer", "gerbil"]

.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: before shift -> giraffe,dog,cat,rabbit,deer,gerbil
shifted (removed) -> giraffe
["dog", "cat", "rabbit", "deer", "gerbil"]

.pop removes last item of array (accepts no params)


console.log("before pop -> " + ani);
var n = ani.pop();
console.log("popped => " + n)
// OUTPUT: before pop -> dog,cat,rabbit,deer,gerbil
popped => gerbil
["dog", "cat", "rabbit", "deer", 1, 2, 3, 4]

.concat concatenates arrays


var jim = [1,2,3,4];
var result = ani.concat(jim);
console.log(result);

.slice returns a shallow copy of a portion of an array into a new array object


var animals = ["dog", "cat", "rabbit", "deer", "mouse", "gerbil", "squirrel", "horse", "cow", "pig"];
var sliceResult = animals.slice(2,4);
console.log(sliceResult);

.splice changes the content of an array by removing existing elements and/or adding new elements.


// Immutable just returns it's value - does not need to be assigned to a var
// Negative index begins count from the end
animals.splice(-1,0, "person");
console.log(animals);

.every() method tests whether all elements in the array pass the test implemented by the provided function


function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

.some() method tests whether some element in the array passes the test implemented by the provided function


function isBiggerThan10(element, index, array) {
  return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true