JavaScript – Simple Functional Programming with Arrays

Dr. Greg Bernstein

Updated February 5th, 2021

More Productivity with Arrays

Learning Objections

  • Get more productive using JavaScript array methods
  • Learn more about practical functional programming
  • Not be intimidated by JavaScript code you will see in the wild

Reference

I visit this page all the time!

MDN JavaScript Array Reference

Don’t reinvent the wheel!

Array Methods 1

  • sort(callback): sorts the elements of an array. Can take a callback function for custom sorting.

  • forEach(callback[, thisObject]): executes callback on every array item.

  • map(callback[, thisObject]): returns a new array of the return value from executing callback on every array item.

Array Methods 2

  • filter(callback[, thisObject]): returns a new array containing the items for which callback returned true.

  • every(callback[, thisObject]): returns true if callback returns true for every item in the array.

  • some(callback[, thisObject]): returns true if callback returns true for at least one item in the array.

Array Methods 3

  • reduce(callback[, initialValue]): applies callback(firstValue, secondValue) to reduce the list of items down to a single value.

  • reduceRight(callback[, initialValue]): works like reduce(), but starts with the last element.

Poll: Similarities?

What did the previous set of array methods have in common?

Things to Avoid

Avoiding Broken Loops

Avoid writing loops for common operations.

Idea: Let the array do its own iteration rather than you writing a loop.

Map

Produces a new array by running a function on each element of the original array.

JavaScript Array.map Example

Wrap a bunch of text in HTML tags

mySs = ["This is a sentence.",
        "A 2nd sentence with more info.",
      "A 3rd, and I could go on and on."];
myPs = mySs.map(function(s){
  return "<p>"+ s + "</p>";
});
console.log(myPs);

More callback parameters

callback(currentValue[, index[, array]])

mySs = ["This is a sentence.",
        "Another sentence with more info.",
      "Event more stuff, and I could go on and on."];
myPs = mySs.map(function(s, i, arr){
  return `<p>${i+1} out of ${arr.length}: ${s} </p>`;
});
console.log(myPs);

Filter

Produces a new array containing only those elements that meet the criteria of the callback function.

filter Example

randArray = [];
for(let i = 0; i < 20; i++) {
  randArray.push(100*Math.random());
} // fill an array with 20 random values
randLess50 = randArray.filter(function(x){
  return x < 50;
}); // grab those less than 50
randGreat50 = randArray.filter(function(x){
  return x > 50;
}); // grab those greater than 50

forEach Example

This is annoying!

myArray = ["Hi", "Hello!", "Hello!!", "WAKE UP!!!"];
myArray.forEach(function(msg, i){
  alert(`${i+1}. ${msg}`);
})

every Example

Good for validation checks, etc

randArray = [];
for(let i = 0; i < 20; i++) {
  randArray.push(100*Math.random());
} // fill an array with 20 random values
allLess50 = randArray.every(function(x){
  return x <= 50;
});
allLess100 = randArray.every(function(x){
  return x <= 100;
});
console.log(`all less than 50? ${allLess50}`);
console.log(`all less than 100? ${allLess100}`);

some Example

Good for validation checks, etc

randArray = [];
for(let i = 0; i < 20; i++) {
  randArray.push(100*Math.random());
} // fill an array with 20 random values
someLess50 = randArray.some(function(x){
  return x <= 50;
});
someGreat100 = randArray.some(function(x){
  return x > 100;
});
console.log(`some less than 50? ${someLess50}`);
console.log(`some greater than 100? ${someGreat100}`);

Reduce Example

Come up with a single thing by iterating over the array

mySs = ["This is a sentence.",
        "Another sentence with more info.",
      "Event more stuff, and I could go on and on."];
message = mySs.reduce(function(acc, s, i, arr){
  return acc + `<p>${i+1} out of ${arr.length}: ${s} </p>\n`;
}, "");
console.log(message);
// reveal.js plugins