Thursday, August 27, 2015

ECMAScript 5 Array Methods

returned value array methods
undefined array.forEach(function)
a new array array.map(function)
a new array array.filter(predicate)
a boolean value array.every(predicate)
a boolean value array.some(predicate)
a value array.reduce(function[, initialValue])
a value array.reduceRight(function[, initialValue])
index|-1 array.indexOf(searchValue[, fromIndex])
index|-1 array.lastIndexOf(searchValue[, fromIndex])

Features common to most of the ECMAScript 5 array methods are:
 array.method(function(value, i, array) [, ref]) { /* function body */ });
  • The methods accept a function as first argument and invoke that function for each element of the array
  • The argument function is invoked with three arguments: the value of the element, the index of the element, the array itself.
  • The methods accept an optional second argument. If it is passed, the first argument function is invoked as a method of the second argument.
  • The methods do not modify the array on which they are called.

1 Array.prototype.forEach()

 array.forEach(function(value, i, array));
  • The forEach() method iterates through an array, invoking a function passed as argument for each array's element
  • The function argument is invoked with three arguments
  • If you want terminate iteration early you should throw an exception
Example
var data = [1,2,3,4,5];
    
// compute the sum of the elements
var result = 0;
data.forEach(function(value) { result += value; });
console.log(result); // 15
    
// square each array element
data.forEach(function(value, i, array) { array[i] = value*value; });
console.log(data); // [1, 4, 9, 16, 25] 

2 Array.prototype.map()

 result_array = array.map(function(value, i, array));
  • The map() method invokes the function you pass with every array element and returns a new array containing the values returned by these invocations.
  • The function you pass to map() is invoked in the same way as the function passed to forEach(), but for the map() method the function should return a value
  • If the array on which map() is invoked is sparse the returned array will be sparse
var data = [1,2,3,4,5];
var squared = data.map(function(x) { return x*x; });
console.log(squared); // [1, 4, 9, 16, 25] 

3 Array.prototype.filter()

 sub_array = array.filter(predicate(x));
  • The array filter() method returns a new array containing a subset of the elements of the array on which it is invoked
  • The function passed to filter() should be a predicate function (a function that returns true or false).
  • The predicate is invoked with every array's element, if the invocation returns true or a truthy value the element is added to the returned array.
  • The array returned by filter is always dense: filter() can be used to close gaps in a sparse array.
Example
var data = [0,1,2,3,4,5,6];
var evenValue = data.filter(function(x) { return x%2==0 });
console.log(evenValue); // [0, 2, 4, 6] 

Example: using filter() to close gaps in sparse arrays
var sparse = [0,1,,3,,5,,7];
var dense = sparse.filter(function() { return true; });
console.log(dense); // [0, 1, 3, 5, 7]

4 Array.prototype.every() and Array.prototype.some()

 booleanValue = array.every(predicate(x));
 booleanValue = array.some(predicate(x));
  • The every() and some() methods apply a predicate function to the elements of an array and then return true or false (every() and some() are array predicates)
  • The every() method returns true if the argument function returns true for every element in the array (like the logic quantifier "for all")
  • The some() method returns true if the argument function returns true for at least one element in the array (like the logic quantifier "there exist").
data = [1,2,3,4,5];

var resultEvery = data.every(function(x) { return x%2 == 0; }) 
console.log(resultEvery); // false: not all values are even.

var resultSome = data.some(function(x) { return x%2 == 0; }) 
console.log(resultSome); // true: there is an even value.

5 Array.prototype.reduce() and Array.prototype.reduceRight()

value = array.reduce(function(x,y) [, initialValue]) {
    // reduce two values into one and return it
});
  • reduce() method iterates through an array and uses a function to combine the array elements and produce a single value. This operation in functional programming is called reduction.
  • the reduce() method takes two arguments: The first argument is the function that performs the reduction. The second optional argument is a value to be passed as argument to the function at first invocation.
Example
var array = [1,2,3,4,5];

// reduce five values into one by adding them - two at a time
var reduction = array.reduce(function(x,y) { return x+y; }, 0);
console.log(reduction); // 15

// reduce five values into one by multiplying them - two at a time
var factorial = array.reduce(function(x,y) { return x*y; }, 1);
console.log(factorial); // 120
 value = array.reduceRight(function(x,y)[, initialValue]);
  • the reduceRight() method works like reduce(), except that it processes array elements from highest index to lowest, from right to left.

using reduce() with objects

reduce() and reduceRight() are not meant only to work with array of numbers. Consider the union() function, this function expects two objects and returns another object that has the properties of both, so it works as a reduction function. We can use reduce(union) to compute the union of an array of objects
/*
 * Copy the enumerable properties of two objects into a new object and return it
 */
function union(p, o) {
    var un = {};
    for(key in p) 
        un[key] = p[key];
    for(key in o) 
        un[key] = o[key];
    return un;
}

var objects = [{eyeColor:"green"}, {hairColor:"brown"}, {race:"Caucasian"}];
var merged = objects.reduce(union);
console.log(merged); // Object {eyeColor: "green", hairColor: "brown", race: "Caucasian"}

6 Array.prototype.indexOf() and Array.prototype.lastIndexOf()

 index = array.indexOf(searchValue[, fromIndex]);
 index = array.lastIndexOf(searchValue[, fromIndex]);
  • indexOf() and lastIndexOf() methods search for the specified value in array's elements
  • They return the index of the found element or -1 if the value is not present
  • indexOf() start the search from the beginning and lastIndexOf() from the end of the array
  • indexOf() and lastIndexOf() methods take a second optional argument specifying the array index where to start the search
array = [1,2,3,1,2,3,1,2,3];
    
var position = array.indexOf(1);
console.log(position); // 0
    
position = array.lastIndexOf(1);
console.log(position); // 6
    
console.log(array.indexOf(4)); // -1: no element with value 4

No comments :

Post a Comment