Array Examples

by jordwms

JavaScript

var myArrayLiteral = [1,2,3];
var myArrayConstructed = new Array(1,2,3);

console.log(myArrayLiteral);
console.log(myArrayConstructed);

// stick to [] to access, since arr.0 will fail
console.log(myArrayLiteral[0]);

// Arrays have a length property
console.log(myArrayLiteral.length);

// Arrays have methods to play with
console.log("Is this an array? ", Array.isArray(myArrayLiteral));

var lastEl = myArrayLiteral.pop();
var firstEl = myArrayLiteral.shift();
console.log(firstEl, lastEl, myArrayLiteral);

myArrayLiteral.push(lastEl);
myArrayLiteral.unshift(firstEl);
console.log(myArrayLiteral);

// Iterating over an array
for (var i=0; i < myArrayLiteral.length; i++) {
     console.log(myArrayLiteral[i]);   
}

myArrayLiteral.forEach(function(el, i, originalArray) {
   console.log(el, i, originalArray); 
});

var myArrayLiteralIsAllEven = myArrayLiteral.every(function(n) {
	return n % 2 === 1;
});

console.log(myArrayLiteralIsAllEven);

var myArrayLiteralHasEven = myArrayLiteral.some(function(n) {
	return n % 2 === 1;
});

console.log(myArrayLiteralHasEven);

var myArrayLiteralEvens = myArrayLiteral.filter(function(n) {
	return n % 2 === 0;
});

console.log(myArrayLiteralEvens);

var myArrayLiteralRaisedByTwo = myArrayLiteral.map(function(n) {
	return Math.pow(n, 2);
});

console.log(myArrayLiteralRaisedByTwo);

var myArrayLiteralReduced = myArrayLiteral.reduce(function(prev, curr) {
	return prev + curr;
});

console.log(myArrayLiteralReduced);