JavaScript Array Methods

forEach

  • Invoked by an array

  • iterates through an array

  • runs a callback function on each value in the array

  • always return undefined

  • Syntax

    1
    2
    // there is a callback method take three parameters
    [1, 2, 3].forEach(function(value, index, array){})
  • Example

    1
    2
    3
    4
    5
    6
    7
    function doubleValues(arr){
    let newArr = [];
    arr.forEach(function(val){
    newArr.push(val * 2)
    });
    return newArr;
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    // Vowel Count
    function vowelCount(str) {
    const splitArr = str.split("");
    let obj = {};
    const vowels = 'aeiou';

    splitArr.forEach(function(letter) {
    if (vowels.indexOf(letter.toLowerCase()) !== -1) {
    if (letter in obj) {
    obj[letter]++;
    } else {
    obj[letter] = 1;
    }
    }
    });
    return obj;
    }

map

  • invoked by an array

  • creates a new array, then iterates through the old array, and run a callback function for each value in the array

  • places the value returned by the callback function to the new array

  • returns the new array (of the same length)

  • syntax

    1
    2
    3
    4
    5
    const arr = [1, 2, 3];

    arr.map(function(value, index, array) {
    return value * 2;
    });
  • map is better than forEach when it is needed to return an array, forEach does better job in doing internal transition

filter

  • Similar to forEach and map, but the result of callback function will always be evaluated into a boolean, if the callback function returns a true, the value will be added to the new array

  • syntax

    1
    2
    3
    arr.filter(function(value, index, array) {
    return value > 2;
    });
  • example

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    function filterByValue(arr, key) { // every object has the given key
    return arr.filter(function(val) {
    return val[key] !== undefined;
    })
    }

    function find(arr, searchValue) {
    return arr.filter(function(val) {
    return val === searchValue;
    })[0];
    }

    function removeVowels(str) {
    const vowels = 'aeiou';
    return str.toLowerCase().split('').filter(function(val){
    return vowels.indexOf(val) === -1;
    }).join('');
    }

some & every

  • some - similar to other functions above, if the callback returns true for at least one single value, the function will return true. Otherwise, return false.

  • every - if the callback returns false for any single value, the entire function return false

  • syntax

    1
    2
    3
    4
    5
    6
    7
    var arr = [1, 2, 3];

    arr.some(function(value, index, array){
    return value < 2;
    });

    // true
  • example

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    function allArrays(arr){
    return arr.every(Array.isArray);
    }
    allArray([[1], [1, 2], [1, 2, 3]]); // true

    function hasAZero(num) {
    return num.toString().split('').some(function(val){
    return val === '0'
    })
    }

    function hasNoDuplicate(arr) {
    return arr.every(function(val){
    return arr.indexOf(val) === arr.lastIndexOf(val);
    });
    }

    function hasCertainKey(arr, key) {
    return arr.every(function(val){
    return key in val;
    });
    }

reduce - turn an array to another data structure

  • accepts a callback function and an optional second parameter

  • iterates through an array, and runs the callback function to each value in the array

  • the first parameter to the callback, often called accumulator, is either the first value in the array or the optional second parameter

  • the return value from the callback becomes the new value of accumulator

  • whatever is returned from the callback function, becomes the new value of the accumulator.

  • syntax

    If there is a second parameter passed to reduce(e.g. 10), the accumulator will be the parameter, and the nextValue will be the first item in the array.

    • Strings

      1
      2
      3
      4
      5
      const names = ['Tim', 'Matt', 'Colt', 'Ellie'];

      names.reduce(function(accumulator, nextValue){
      return accumulator += ' '+nextValue;
      }, 'The instructors are')
    • Object - build a counter

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      const arr = [5, 4, 1, 4, 5];

      arr.reduce(function(accumulator, nextValue){
      if (nextValue in accumulator) {
      accumulator[nextValue]++;
      } else {
      accumulator[nextValue] = 1;
      }
      return accumulator;
      })
    • vowel count

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      function vowelCount(str) {
      const vowels = 'aeiou';
      return str.split('').reduce(function(acc, next) {
      if (vowels.indexOf(next.toLowerCase()) !== -1) {
      if (next in acc){
      acc[next]++;
      }else {
      acc[next] = 1;
      }
      }
      return acc;
      }, {})
      }