With Javascript 1.6 we have some new ways to manipulate arrays. To check whether your favourite browser supports these consult this compatibility table.

indexOf() and lastIndexOf()

Avid readers will recognize indexOf() and lastIndexOf() from a previous post on string manipulation. These methods are now available for arrays and are used to search an array for a value.

With indexOf we look for the first occurrence of a value and return its index value.

var clashAlbums=new Array("The Clash","Give 'em Enough Rope","London Calling","Sandinista!","Combat Rock")
var findAlbum = clashAlbums.indexOf('Combat Rock');
document.getElementById('showPopped').innerHTML = findAlbum;

JSFIDDLE Demo

With lastIndexOf we look for the last occurrence of a value and return its index value – ie starts the search from the end of the array.

var clashAlbums=new Array("The Clash","Give 'em Enough Rope","London Calling","Sandinista!","Combat Rock")
var findAlbum = clashAlbums.lastIndexOf('Combat Rock');
document.getElementById('showPopped').innerHTML = findAlbum;

JSFIDDLE Demo

With both indexOf() and lastIndexOf(), a value of -1 is returned if no match is found.

forEach

The forEach loop makes looping around arrays nice and easy. In the following example album is the variable name I have assigned to every array value as it loops through the array.

clashAlbums.forEach(function(album){
    document.getElementById('display').innerHTML += album;
    document.getElementById('display').innerHTML += "<br>";
});

JSFIDDLE Demo

map()

The map() method will loop the contents of an array and call a given callback function using the current value. The results of this are then stored in an array which is the return value of map().

For example say we have a set of scores out of 150 and we want to create an array of these results as a percentage.

// marks out of 150
var myScores = [145,111,122,78,56,78,130];
// new array to hold percentage scores
var myScoresPercent;
myScoresPercent = myScores.map(function(myScore){
   return (myScore / 150) * 100  
});

Notice the use of an anonymous function as the parameter inside map().

JSFIDDLE Demo

As you can see from the jsfiddle the numbers returned are correct but it would be better to round the numbers to the nearest integer and add the % character. To do so I rewrite the above this time using a named function as opposed to an anonymous function.

function sortPercent(myScore){
    percentScore = (myScore / 150) * 100;
    percentScore = Math.round(percentScore);
    percentScore += "%";
    return percentScore;  
}
// marks out of 150
var myScores = [145,111,122,78,56,78,130];
var myScoresPercent;
myScoresPercent = myScores.map(sortPercent);

JSFIDDLE Demo

every()

With every() a callback function is called for every value in the array to check some criteria is meet. If any value in the array does not meet the criteria false is returned otherwise a value of true is returned. The following uses an anonymous function.

var myScores = [145,111,122,78,56,78,130];
var above50 = myScores.every(function(myScore){
   return (myScore > 50)
})
document.getElementById('display').innerHTML = above50;

As all our values are over 50 then true is returned.

JSFIDDLE Demo

Alternatively we could use a named function and we’ll change this to test if all the values are above 80.

function above80(myScore){
    return (myScore > 80);
    
}
// marks out of 150
var myScores = [145,111,122,78,56,78,130];
var over80 = myScores.every(above80)

JSFIDDLE Demo

some()

With some() we check to see if one or more values match a given criteria and then return true if there is a match. Again your callback function can be anonymous or named – here it is named.

function above80(myScore){
    return (myScore > 80);
    
}
// marks out of 150
var myScores = [145,111,122,78,56,78,130];
var over80 = myScores.some(above80)

JSFIDDLE Demo

filter()

While every() and some() test an array meets some criteria with filter() we can create a new array containing the values that meet the criteria.

function above80(myScore){
    return (myScore > 80);
    
}
// marks out of 150
var myScores = [145,111,122,78,56,78,130];
var over80 = myScores.filter(above80)

In the above a new array ‘over80’ will be populated with those values over 80.

JSFIDDLE Demo

reduce()

We are doing a lot of work with numbers here and reduce() is no exception. This acts as an accumulator ‘reduces’ the values in the area into one value. The calculations you perform are based on the logic in your callback function. A simple example would be to add together all the value is in the array.

// marks out of 150
var myScores = [145,111,122,78,56,78,130];
var totalScore = myScores.reduce(function(prev, current){
    return prev + current;
})

Note that on the first iteration reduce() cleverly uses the first value in the array as the ‘previous’ value – as obviously there was no previous value at that point. From that point on the ‘previous’ value is the value of the return from the last callback.

JSFIDDLE Demo

Other use cases would be to find the largest value:

var myScores = [145,111,122,78,56,78,130];
var totalScore = myScores.reduce(function(prev, current){
    return ( prev > current ? prev : current );
})

JSFIDDLE Demo

.. or indeed the smallest.

var myScores = [145,111,122,78,56,78,130];
var totalScore = myScores.reduce(function(prev, current){
    return ( prev < current ? prev : current );
})

JSFIDDLE Demo

We also have a variant of reduce() called reduceRight() that does the same but works through the values from right to left – ie backwards.

You’ll find more about arrays regarding basics, split/join and traditional methods.

Leave a Comment