High Order Array Methods

Page section: posts

This is from 43.25 on the first video and covers forEach(), map() and filter()

The syntax for these is the same:

arrayName.forEach((item)=> {
    //some code...
});

forEach()

The forEach() method is used to iterate through an array and outputs via a function.

This is an example of the syntax for a high order array method. With an array called myArray it would be:

myArray.forEach(function(item){
  console.log(item);
});

Here is the syntax using an arrow function:

myArray.forEach((item) => {
  newP[0].innerHTML += `<div>${item}</div>`;
});

An even more abbreviated example:

myArray.forEach((item) => console.log(item));

NB. The word item could have been any valid JS variable name. Often the singular of the array name is used. For example in an array called dogs then dog could be used.

Second parameter

The forEach() method can also take a second parameter. So the first parameter is the value of each array item the second paramenter is it’s index or place number in the array, starting with 0 for the first array item.

outputs the array below and, using the forEach loop, to the console.

You can also use it like so:

["Bilbo", "Gandalf", "Nazgul"].forEach(alert);

The buttons below use the code above but also using map and filter which makes no difference as set.

Use any function

You can also use any function with the forEach method as a callback function as a parameter. For example if you want to use a function previouly declared and named myCoolFunction then:

myArray.forEach(myCoolFunction);

You might want to use the value of each array item in this function so as before think of a variable name, like item here, and add it as a parameter of the function:

myArray.forEach(myCoolFunction(item));

Some of the examples below use a JS object todos

View the todos object
const todos = [
    {
        id: 1,
        text: 'Take out rubbish',
        isCompleted: true,
    },
    {
        id: 2,
        text: 'Meet with boss',
        isCompleted: true,
    },
    {
        id: 3,
        text: 'Dental appointment',
        isCompleted: false,
    }
];

map()

The map() method is extremely similar to forEach(). The key difference is that map() creates a new array.

This means you can store the result of map() in a variable whereas you can’t with forEach()

let myNames = ['Bob', 'Johan', 'Tobble', 'Snod', 'Trouser' ]

let forEachNames = myNames.forEach(name => {name.toLowerCase()} );
console.log(forEachNames);
// undefined

let mapNames = myNames.map( name => name.toLowerCase() );
console.log(mapNames);
// [ 'Bob', 'Johan', 'Tobble', 'Snod', 'Trouser' ]

The map() method allows you to map each item in an array to something else.

In this example each element is mapped to <li> tags:

const viverrids = ['oyan', 'civit', 'gennet', 'binturong'];

const vivListItems = viverrids.map(animal => '<li>' + animal + '</li>');

// to add outer ul tags you might use join()...
const finalCode = '<ul>' + vivListItems.join('') + '<ul>';

The map method creates a new array from an array. It therefore makes sense to store the output in a new variable.

Here it is used on an array of objects (todos) to get all the values of text and store them in a new array called todosText.

const todoText = todos.map((item) => {
            return item.text
    }); 
            
    console.log(todoText);

filter()

The filter method also creates a new array, this time based on a condition.

OR it creates a new array of items from an array that pass a given test. A function can be used as a parameter for the test.

const todoCompleted = todos.filter(function(todo) {
    return todo.isCompleted === true;
});

console.log(todoCompleted);

Chaining multiple array methods together

It’s also possible to chain several of these together.

const todoCompleted = todos.filter(function(todo) {
    return todo.isCompleted === true;
});.map(function(todo){
    return todo.txt;
})

More on filters in the Traversy Media video at 45 mins as well as a whole video on high order array methods.

A full list of array methods, all time stamped so easily searchable, is portEXE’s video:

View contents of: /static/js/temp.js
// another temporary js file
View contents of: /static/js/tryout-arrays.js
const fruit = ["apples", "bananas", "cantaloupe", "dorians"];

const scientificFruit = [
  "Bell pepper",
  " Chile pepper",
  " Corn kernel",
  " Cucumber",
  " Eggplant",
  " JalapeƱo",
  " Olive",
  " Pea",
  " Pumpkin",
  " Squash",
  " Tomato",
  " Zucchini",
];

const todos = [
  {
    id: 1,
    text: "Take out rubbish",
    isCompleted: true,
  },
  {
    id: 2,
    text: "Meet with boss",
    isCompleted: true,
  },
  {
    id: 3,
    text: "Dental appointment",
    isCompleted: false,
  },
];

function showFruit() {
  document.getElementById("fruitlist").innerHTML = fruit;
}

function fruitLoops(frt) {
  document.getElementById("fruit-loops").innerHTML += frt + '<br>';
}

const butt1 = document.getElementById("listfruit");

butt1.addEventListener("click", () => {
  document.getElementById("fruitlist").innerHTML = fruit;
});

const butt2 = document.getElementById("fruit2");

butt2.addEventListener("click", function () {
  document.getElementById("fruitlist").innerHTML = fruit[1];
});

const butt3 = document.getElementById("scientific");

butt3.addEventListener("click", function () {
  document.getElementById("fruitlist").innerHTML = scientificFruit;
});

const butt39 = document.getElementById("copying");

butt39.addEventListener("click", function () {
  const otherFruit = fruit.slice(1, 3);
  console.log("what apphen?");
  alert(`A new array called otherFruit now contains ${otherFruit}`);
});

// For buttons showing Array Methods

let myVar = [[1, "tree"], 2, 3, 4, 5, 6];
const mySubVar = ["frog", "Linsang", "stink badger"];

const showMyVar = document.getElementById("show-my-var");
const smvList = document.getElementById("smv-list");

function listMyVar() {
  smvList.innerHTML = ``;
  for (let i = 0; i < myVar.length; i++) {
    smvList.innerHTML += `<li>${myVar[i]}</li>`;
  }
}

showMyVar.addEventListener("click", () => {
  listMyVar();
});

const resetMyVar = document.getElementById("reset-my-var");

resetMyVar.addEventListener("click", () => {
  myVar = [[1, "tree"], 2, 3, 4, 5, 6];
  listMyVar();
  //   alert("reset");
});

Table of Contents