[JavaScript] Arrays – ECMAScript5

ECMAScript5 provides new methods for iteration, filtering, and searching. In previous version, to perform these tasks, you need to iterate each item using the “for” loop and do the appropriate works. Now you can create the delegate function and pass as an argument to one of the new methods. The code becomes much cleaner.

1. ECMAScript5 Array Methods

ECMAScript5 provides the following new methods:

  • forEach()
  • map()
  • filter()
  • every() / some()
  • reduce() / reduceRight()
  • indexOf() / lastIndexOf()

Most new methods accept 2 arguments : a call-back function and an object for “this” in the function.

The call-back function accepts up to 3 arguments.

  • value : the current element in an array
  • index : the index of an element in an array
  • array : array being traversed

The return value of the function is very important but each method handles the return value differently.

 

2. forEach()

The “forEach()” method iterates an array and invokes the function for each element.

function calTotal(value, index) {
  this.total += value;
}
$(document).ready(function () {
  var nums = [1, 2, 3, 4, 5];
  var sum = { total: 0 };
  nums.forEach(calTotal, sum);
  alert(sum.total); // 15
});

 

3. map()

ECMAScript5 methods do not modify the array itself. You can do it by using the third argument of the function. But this approach is not recommended at all. You should not touch an array while it is iterated.

The better way is the “map()” method. It returns a new array. The return value of the call-back function maps to the element in the new array.

function calSubtotal(value, index) {
  this.total += value;
  return this.total; // subtotal
}
$(document).ready(function () {
  var nums = [1, 2, 3, 4, 5];
  var sum = { total: 0 };
  var subTotals = nums.map(calSubtotal, sum);
  alert(subTotals.toString()); //1,3,6,10,15
  alert(sum.total); // 15
});

 

4. filter()

The “filter()” method returns an array whose elements matches the condition provided as a function. The function should return true or false.

var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var oddNums = nums.filter(function (v) { return v % 2 == 1; });
var evenNums = nums.filter(function (v) { return v % 2 == 0; });
alert(oddNums.toString()); //1,3,5,7,9
alert(evenNums.toString()); //2,4,6,8

 

5. every() / some()

These 2 methods return true or false when all or some elements of an array match the provided predicate function.

var nums = [1, 2, 4];
var isAllOdd = nums.every(function (v) { return v % 2 == 1; });
var isSomeOdd = nums.some(function (v) { return v % 2 == 1; });
alert(isAllOdd); //false
alert(isSomeOdd); //true

These methods are very useful when you verify the data.

var nums = [1, "Hello", 4];
var isAllNumbers = !(nums.some(isNaN));
alert(isAllNumbers); //false

 

6. reduce() / reduceRight()

The “reduce()” method is used to produce a single result using all elements in an array. For each step, the result is accumulated.

  • reduce(function, initialValue)
  • reduceRight(function, initialValue)

The parameters of the call-back function are also different. The first parameter is the accumulated result so far. The second one is a value and the third one is an index.

function calSum(result, value) {
  return result + value;
}
$(document).ready(function () {
  var nums = [1, 2, 3, 4, 5];
  alert(nums.reduce(calSum, 0)); // 15
  alert(nums.reduce(function(r, v) { return r*v; }, 1));  // 120
});

 

7. indexOf() / lastIndexOf()

Searching the value in an array becomes very easy now.

  • indexOf(value, startIndex)
  • lastIndexOf(value, startIndex)

They return the index of the first matching element.

var nums = [1, 2, 1, 2, 3, 1, 2, 1];
var index = -1;
var index = nums.indexOf(1); // searching 1
while (index != -1) { // if not found, -1 is returned
  alert("1 is located in nums[" + index + "]."); // 0,2,5,7
  index = nums.indexOf(1, index+1);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s