Advanced array functions

Objectives

  • Use the Array.forEach function
  • Use the Array.every function
  • Use the Array.some function
  • Use the Array.map function
  • Use the Array.filter function
  • Use the Array.reduce function
  • Use the Array.sort function

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.

  • forEach(func): processes each element of array by sending it to func
  • every(func): returns true if and only if each element of the array sent to func returns true
  • some(func); returns true if any element of the array sent to func returns true
  • map(func): returns an array consisting of each element of the original array processed by func
  • filter(func): returns a new array consisting of only those elements which return true when sent to func
  • reduce(func(previous, current, index, array), initial): computes a single value for an array using initial value to start, and then computing a new value given the previous computed value to this point and the current array element value
  • sort(func(a,b)): uses func to determine the sort order; func is sent two array elements and is supposed to return < 0 if the first element comes first, > 0 if the first element comes second, and 0 if the elements are equal

Examples