Advanced array functions

Objectives

Overview

The functions covered on this page take callback functions as arguments. The callback functions are automatically passed each element in the array. These functions could be implemented using iteration (such as a for loop), but this syntax is more concise.

// set up array for use var ar = ["Don","Ralph","Gale"]; // use forEach to display each item in the array ar.forEach(function(a) { console.log(a); }); // displays: // Don // Ralph // Gale // check to see if 'a' is the second letter of EVERY array element ar.every(function(a) { return a.charAt(1) == 'a'; }); // returns: false // check to see if 'a' or 'o' is the second letter of EVERY array element ar.every(function(a) { c = a.charAt(1); return c == 'a' || c == 'o'; }); // returns: true // check to see if 'a' is the second letter of ANY array element ar.some(function(a) { return a.charAt(1) == 'a'; }); // returns: true // check to see if 'e' is the second letter of ANY array element ar.some(function(a) { return a.charAt(1) == 'e'; }); // returns: false // convert each element of the array to uppercase ar.map(function(a) { return a.toUpperCase(); }); // returns: ["DON", "RALPH", "GALE"] // filter out those elements which do not have 'a' as their second letter // note the chaining of functions to display the result ar.filter(function(a) { return a.charAt(1) == "a"; }).forEach(function(a) { console.log(a); }); // displays: // Ralph // Gale // concatenates all the elements of the array ar.reduce(function(pv, cv) { return pv + cv; }); // returns: "DonRalphGale" // concatenates all the elements of the array and adds an initial value ar.reduce(function(pv, cv) { return pv + cv; }, "Concatenated: "); // returns: "Concatenated: DonRalphGale" // computes a single value from all the array elements // total = 1*1 + 2*2 + 3*3 + 4*4 [1,2,3,4].reduce(function(pv, cv, ndx) { return pv + cv * (ndx+1); }); // returns: 30 // set up array for sorting demonstrations ar = [1,2,3,4,5,6,7,8,9,10]; // this comparison function sorts in decreasing order ar.sort(function(a,b) { return b-a; }); // returns: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] // this comparison function gives a random order ar.sort(function(a,b) { return [-1,1][Math.floor(Math.random() * 2)]; }); // returns: [5, 8, 2, 9, 7, 6, 10, 4, 3, 1]