Advanced Array Methods

Summary

  • 1) forEach (returns defined)
  • 2) map (returns a new array of the same length)
  • 3) filter (The result of the callback will ALWAYS be a boolean)
  • 4) some and every (The result of the callback will ALWAYS be a boolean)
  • 5) reduce (whatever returns is stored in accumulator)
  • Methods 1-4: only accept 1 parameter which is a callback function
    • [].ArrayMethods(function(val, index, array){});
    • We can call the parameters to the callback whatever we want!
    • We do not always need all three parameters, use whichever ones you need, just remember the order is important!
  • Method 5 i.e. reduce accepts an optional 2nd parameter
    • [].reduce(function(accumulator, nextVal, index, array){}, optionParameter);

forEach()

  • iterates through an array
  • Runs a callback function on each value in the array
  • returns undefined

Example: Implement my own forEach

In [24]:
function myForEach(arr, callback){
  for (var i=0;i<arr.length;i++){
    callback(arr[i], i, arr);
  }
}

Example:

In [25]:
function halfValues(arr){
  var newArr = [];
  arr.forEach(function(val){
    newArr.push(val/2);
  });
  return newArr;
}

map()

  • Creates a new array
  • Iterates through an array
  • Runs a callback function for each value in the array
  • Adds the result of that callback function to the new array
  • Returns the new array
  • map ALWAYS returns a new array of the SAME length

Example: implement my own map

In [26]:
function myMap(arr, callback){
  var newArr=[];
  for (var i=0; i<arr.length; i++){
    newArr = push(callback(arr[i], i, arr));
  }
  return newArr;
}

filter()

  • Creates a new array
  • Iterates through an array
  • Runs a callback function on each value in the array
  • If the callback function returns true, that value will be added to the new array
  • If the callback function returns false, that value will be ignored from the new array
  • The result of the callback will ALWAYS be a boolean

Example: Implementation of filter

In [27]:
function myFilter(arr, callback){
  var newArr = [];
  for (var i=0; i<arr.length; i++){
    if(callback(arr[i], i, array)){
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

Example 1

In [28]:
var arr = [1,2,3];
arr.filter(function(value, index, array){
  // no need for an if statement, just return an expression that evaluates to true or false!
  return value > 2;
});
Out[28]:
[ 3 ]

Example 2

In [29]:
var instructors = [{name: "Elie"},
                   {name: "Tim"},
                   {name: "Matt"},
                   {name: "Colt"}
                  ];

instructors.filter(function(value, index, array){
    return value.name.length > 3;
});
Out[29]:
[ { name: 'Elie' }, { name: 'Matt' }, { name: 'Colt' } ]

some()

  • Iterates through an array
  • Runs a callback on each value in the array
  • If the callback returns true for at least one single value, return true
  • Otherwise, return false
  • The result of the callback will ALWAYS be a boolean

Example: Implementation of some

In [30]:
function mySome(arr, callback){
  var newArr = [];
  for (var i=0; i<arr.length; i++){
    if(callback(arr[i], i, array)){
      return true;
    }
  }
  return false;
}

every()

  • Iterates through an array
  • Runs a callback on each value in the array
  • If the callback returns false for any single value, return false
  • Otherwise, return true
  • The result of the callback will ALWAYS be a boolean

Implement my own every

In [31]:
function myEvery(arr, callback){
  var newArr = [];
  for (var i=0; i<arr.length; i++){
    if(callback(arr[i], i, array) === false){
      return false;
    }
  }
  return true;
}

Interview Question

  • Question:
In [32]:
function allArrays(arr){
  return arr.every(Array.isArray);
}
In [33]:
allArrays([[1], [2], [3,4]]);
Out[33]:
true
In [34]:
allArrays([[1], [2], {}]);
Out[34]:
false

Reduce()

  • Convert an array into other data structure such as a string, a number, an object, an array of arrays etc.
  • Accepts a callback function and an optional second parameter
  • Iterates through an array
  • Runs a callback on each value in the array
  • The first parameter to the callback is either the first value in the array or the optional second parameter
  • The first parameter to the callback is often called "accumulator"
  • The returned value from the callback becomes the new value of accumulator
  • Whatever is returned from the callback function, becomes the new value of the accumulator!

Example

[1,2,3].reduce(function(accumulator, nextvalue, index, array){
  //what is returned inside here will be the accumulator value in the next iteration
}, opt2ndParam);

Example: convert array to number

In [35]:
var arr = [1,2,3,4,5];

arr.reduce(function(accumulator, nextValue){
  return accumulator + nextValue;
});
Out[35]:
15
accumulator nextValue returned value
1 2 3
3 3 6
6 4 10
10 5 15

Example: convert array to number (2nd params)

In [36]:
var arr = [1,2,3,4,5];

arr.reduce(function(accumulator, nextValue){
  return accumulator + nextValue;
},10);
Out[36]:
25
accumulator nextValue returned value
10 1 11
11 2 13
13 3 16
16 4 20
20 5 25

Example: convert array to strings (2nd params)

In [37]:
var names = ['Tim', 'Matt', 'Colt', 'Elie'];

names.reduce(function(accumulator, nextValue){
  return accumulator += ' ' + nextValue;
},'The instructors are');
Out[37]:
'The instructors are Tim Matt Colt Elie'
accumulator nextValue returned value
"The instructors are" "Tim" "The instructors are Tim"
"The instructors are Tim" "Matt" "The instructors are Tim Matt"
"The instructors are Tim Matt" "Colt" "The instructors are Tim Matt Colt"
"The instructors are Tim Matt Colt" "Elie" "The instructors are Tim Matt Colt Elie"

Example: convert array to object (2nd params)

In [38]:
var arr = [5,4,1,4,5];

arr.reduce(function(accumulator, nextValue){
  if(nextValue in accumulator){
    accumulator[nextValue]++;
  } else {
    accumulator[nextValue] = 1;
  }
  return accumulator;
},{});
Out[38]:
{ '1': 1, '4': 2, '5': 2 }
accumulator nextValue returned value
{} 5 {5:1}
{5:1} 4 {5:1, 4:1}
{5:1, 4:1} 1 {5:1, 4:1, 1:1}
{5:1, 4:1, 1:1} 4 {5:1, 4:2, 1:1}
{5:1, 4:2, 1:1} 5 {5:2, 4:2, 1:1}

Using reduce in a function

Example 1:

In [39]:
function sumOddNumbers(arr){
  return arr.reduce(function(accumulator,nextValue){
    if(nextValue % 2 !== 0){
      accumulator += nextValue;
    }
      return accumulator;
    },0);
}

sumOddNumbers([1,2,3,4,5]);
Out[39]:
9

Example 2:

In [40]:
function createFullName(arr){
  return arr.reduce(function(accumulator, nextValue){
    accumulator.push(nextValue.first + " " + nextValue.last);
    return accumulator;
  }, []);
}

createFullName([{first:"Colt", last:"Steele"}, {first:"Matt", last:"Lane"}]);
Out[40]:
[ 'Colt Steele', 'Matt Lane' ]