A typical day of a javascript developer has some sort of Array operation that needs to be done. The choicest way of doing this is to loop through it, however ECMASCRIPT5 has a lot of convenience methods for almost all of the needs. Some of these methods have existed in the previous versions as well. So, the next time you start writing some loop logic, try few of the existing methods that gets the job done in a more elegant and functional way.

The Array.isArray() method returns true if an object is an array, false if it is not.

Array.isArray('hello'); // Result: false
Array.isArray('hello'.split('')); // Result: true

The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments. Concatenating array(s)/value(s) will leave the originals untouched. Furthermore, any operation on the new array will have no effect on the original arrays, and vice versa.

var alpha = ['a', 'b', 'c'];
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3]

The every() method tests whether all elements in the array pass the test implemented by the provided function. The every method will iterate elements of the Arry only until it finds an element that does not satisfy the condition.

function isEven(element, index, array) {
  return element%2===0;
}
[12, 5, 8, 130, 44].every(isEven); // Result: false

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

function isEven(element, index, array) {
  return element%2===0;
}
[12, 5, 8, 130, 44].some(isEven); // Result: true
[1 ,5 ,7].some(isEven); // Result: false

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

function isEven(element, index, array) {
  return element%2===0;
}
[12, 5, 8, 130, 44].filter(isEven); // Result: [12,8,130,44]

The forEach() method executes a provided function once per array element.

function isEven(element, index, array) {
  console.log( element%2===0 );
}
[12, 5, 8, 130, 44].forEach(isEven); // Result: true false true true true

The map() method creates a new array with the results of calling a provided function on every element in this array.

var numbers = [1, 4, 9];
numbers.map(Math.sqrt); // [1, 2, 3]
var numbers = [1, 4, 9];
function addOne(val){return val+1;}
numbers.map(addOne); // [2, 5, 10]

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value. It also takes an optional parameter, that will be used as the first argument to the first call of the callback.

var val = [1,4,9].reduce(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
});
console.log(val); //14
var val = [1,4,9].reduce(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
},11);
console.log(val); //25

The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) has to reduce it to a single value.It also takes an optional parameter, that will be used as the first argument to the first call of the callback.

var val = [1,4,9].reduceRight(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
});
console.log(val); //14
var val = [1,4,9].reduceRight(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
},11);
console.log(val); //25

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

[12, 5, 8, 130, 44].indexOf(130); // Result: 3
[12, 5, 8, 130, 44].indexOf(10); // Result: -1

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex. It also takes an optional parametert that specified the index at which to start searching backwards. Defaults to the array’s length.

var array = [1, 3, 5, 7, 3];
array.lastIndexOf(3);     // 4
array.lastIndexOf(7);     // -1
array.lastIndexOf(3, 3);  // 1
array.lastIndexOf(3, -2); // 1
array.lastIndexOf(3, -1); // 4

The join() method joins all elements of an array into a string. It takes an optional parameter used as a separator, the default is a comma.

[1,2,3,4].join(); // Result: 1,2,3,4
[1,2,3,4].join('$'); // Result: 1$2$3$4

The pop() method removes the last element from an array and returns that element.

var numbers = [1, 4, 9];
var poppedOut = numbers.pop();
console.log(poppedOut); // 9
console.log(numbers); // [1,4]

The push() method adds one or more elements to the end of an array and returns the new length of the array.

var numbers = [1, 4, 9];
var newLength = numbers.push(20);
console.log(newLength); // 4
console.log(numbers); // [1,4,9,20]

The shift() method removes the first element from an array and returns that element. This method changes the length of the array.

var numbers = [1, 4, 9];
var poppedOut = numbers.shift();
console.log(poppedOut); // 1
console.log(numbers); // [4,9]

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

var arr = [1, 2];
 
arr.unshift(0); // result of call is 3, the new array length
// arr is [0, 1, 2]

The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.

var numbers = [1,4,9];
numbers.reverse();
console.log(numbers); //[9,4,1]

The sort() method sorts the elements of an array in place and returns the array. The default sort order is according to string Unicode code points. It also takes a optional callback method, that can do the compare logic.

var arr = [12, 5, 8, 130, 44]
arr.sort(); 
console.log(arr); // Result: [12, 130, 44, 5, 8]
//Typical compare function
function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

The slice() method returns a shallow copy of a portion of an array into a new array object. It takes two optional parameters, begin and end index. The end index is exclusive.

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);
// citrus contains ['Orange','Lemon']

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

var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
 
// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed
 
// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']

More in depth information can be found on the Mozilla Developer Network

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=""> <s> <strike> <strong>