Advanced Array Methods

Arrays naturally lend themselves to procedures involving iteration; we'll often find ourselves needing to process each item in an array in sequence with tasks that share particular iterative formats.

Several of these common tasks are implemented as array methods, which we'll explore below:


Every / Some


Sometimes, we may wish to see if some condition is met for *every* or *at least 1* element in an array, which can require us to make a cumbersome loop that isn't reusable. Rather, we have two array methods that can help.

For a JavaScript array arr, the arr.some(function) returns true if *any* array element is true for the specified function of the format: function(element) where element is the current element being examined (and false otherwise).

For a JavaScript array arr, the arr.every(function) returns true if *every* array element is true for the specified function of the format: function(element) where element is the current element being examined (and false otherwise).

Note: there are other optional arguments to these methods, but you can consult the documentation to see them.

In either case, the given function is called for every element in the calling array; the function will then return either a truthy or falsy value for each element, which will then be processed by either .some() or .every().

For example, suppose we have arrays of strings and want to know if any (i.e., .some()) or every (i.e., .every()) element contains a space.

  let arrNoSpaces = ["No", "Spaces", "Here!"],
      arrSpaces   = ["Woah", " S p a c e y", "   bro"];
  
  function hasSpace (element) {
    return element.indexOf(" ") != -1;
  };
	
  console.log(arrNoSpaces.some(hasSpace));   // false
  console.log(arrNoSpaces.every(hasSpace));  // false
  console.log(arrSpaces.some(hasSpace));     // true
  console.log(arrSpaces.every(hasSpace));    // false

Using arrow functions, we could also do the following:

  let arrNoSpaces = ["No", "Spaces", "Here!"],
      hasSpace    = (element) => element.indexOf(" ") != -1;
  
  console.log(arrNoSpaces.some(hasSpace));   // false
  console.log(arrNoSpaces.every(hasSpace));  // false
  console.log(arrSpaces.some(hasSpace));     // true
  console.log(arrSpaces.every(hasSpace));    // false

Or, if we were only using the hasSpace function once:

  let arrNoSpaces = ["No", "Spaces", "Here!"];
  // [!] "Anonymous" function syntax
  console.log(arrNoSpaces.some((element) => element.indexOf(" ") != -1));

Note: arrow functions can be substituted anywhere one of the following functions is expected and be used anonymously, meaning the function is defined, used where expected, but then discarded afterwards since there is no name assigned to it (like in the example immediately above).


Map


Suppose we wish to obtain a new array from an existing one via some sort of transformation or as a result of each element in an existing array; this can be thought of as mapping an operation to each element in the existing array, and obtaining the new one as a result.

For a JavaScript array arr, the arr.map(function) method returns a new array composed of the given function being called on each element of arr, and whose returned values are collected in the new array.

For example, suppose we have an array of strings and want to add an exclamation mark to the end of each; we could do the following:

  function addExcitement (element) {
    return element + "!";
  }

  let boringArr = ["no", "fun", "here"],
      excitingArr = boringArr.map(addExcitement);
	
  console.log(excitingArr);

Filter


For some tasks, we may wish to obtain an array with all elements removed that do not fit some criteria; for this purpose, we can use an array's filter method.

For a JavaScript array arr, the arr.filter(function) method returns a new array composed of all of arr's elements for which the given function (parameterized by each element) returns true.

For example, suppose we wish to remove all objects from an array of objects such that the isDead property is true; we could perform the following:

  function cryptify (element) {
    return !element.isDead;
  }

  let zoms = [
        {name: "ZomA", isDead: true},
        {name: "ZomB", isDead: false},
        {name: "ZomC", isDead: true}
      ],
      undeadZoms = zoms.filter(cryptify);
	
  console.log(undeadZoms);


Ternary Expressions

Sometimes, we wish to assign a variable some value that is conditional on another, which we would traditionally do via the following:

  // [X] Warning: poor style:
  let pet = "dog",
      response;
  
  if (pet === "dog") {
    response = "Aww pupper!";
  } else {
    response = "No dog, not interested!";
  }
  
  alert(response);

The if-statement here is actually overkill; instead, we can use what's called a ternary expression:

A ternary expression returns one value if the given condition is truthy, or another if it is falsy, and is written: (cond) ? truthyVal : falsyVal

So, we can re-write our example above as:

  let pet = "dog",
      response = (pet === "dog") ? "Aww pupper!" : "No dog, not interested";
  
  alert(response);

No if-statement required; beautiful!



  PDF / Print