Web Development Boot Camp: Week 5 (2)
By: Youra Cho
Tags: Foreach, Map, Reduce, JavaScript, Filter

Dive into JavaScript: Array methods with explanations and examples

image credit: developer howto

The array methods below require the callback function as an argument.

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action(source: MDN).

In the array method, a callback is used to execute each element.

To invoke the callback function, you can input just the name of the callback function inside of the method and code separately in a function with that function name as in array.filter(isPrime). Otherwise, input the whole codes itself into the method like arr.map(i => i*10).

The map() method returns a new array with each element being the result of the callback function.

// syntax let new_array = arr.map(callback(currentValue[, index[, array]]), thisArg])

// example1 let arr = [1,2,3,4,5];

let newArray = arr.map(i => i*10);

> newArray

[10, 20, 30, 40, 50]

// example2 let numbers = [4, 9, 16, 25]

let roots = numbers.map(num => Math.sqrt(num));

> roots

[2, 3, 4, 5]

// example3 let persons = [

{firstname : "Malcom", lastname: "Reynolds"},

{firstname : "Kaylee", lastname: "Frye"},

{firstname : "Jayne", lastname: "Cobb"}

]; function fullname(person) {

return [person.firstname, person.lastname].join(" ");

} let fullnames = persons.map(fullname);



> console.log(fullnames);

["Malcom Reynolds", "Kaylee Frye", "Jayne Cobb"]

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

// syntax let newArray = arr.filter(callback(element[, index, [array]])[, thisArg]) // example1 let ages = [32, 33, 16, 40];

let checkAdult = ages.filter(age => age >= 18);

console.log(checkAdult);

> [32, 33, 40]

// example2: isPrime algorithm let array = [4, 6, 8, 9, 12, 53, -17, 2, 5, 7, 31, 97, -1, 17];

function isPrime(num) {

for(let i = 2; i < parseInt(Math.sqrt(num)) + 1; i++)

if(num % i === 0) return false;

return num > 1;

} > console.log(array.filter(isPrime));

[53, 2, 5, 7, 31, 97, 17]

The reduce() method executes a reducer function on each element of the array, resulting in a single output value from the reduction. The callback takes at least two arguments: accumulator and currentValue. An initial value is optional. If no initialValue is supplied, the first element in the array will be used as the initial accumulator value. But if the array is empty and no initialValue is provided, TypeError will be thrown.

// syntax arr.reduce(callback(accumulator, currentValue[, index[, array]] )[, initialValue])

// example1 let arr = [1,2,3,4,5];

let total = arr.reduce((acc, item) => acc += item, 0); // returns 15

// example2: Flatten an array of arrays let flattened = [[0, 1], [2, 3], [4, 5]].reduce((acc, cur) =>

acc.concat(cur), []); > console.log(flattened)

[0, 1, 2, 3, 4, 5]

// example3: Counting instances of values in an array

let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']



let countedNames = names.reduce(function (allNames, name) {

if (name in allNames) {

allNames[name] += 1

}

else {

allNames[name] = 1

}

return allNames

}, {}) > console.log(countedNames)

{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}

The forEach() method executes a provided function once for each array element. The forEach() method has no return value. It’s undefined. Take a look at example 2 below.

// syntax arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

// example1 let months = ["Jan", "Feb", "March", "April"]; months.forEach((element, index) => console.log(index+1 + ': ' + element)); 1: Jan

2: Feb

3: March

4: April

// example2: A comparison with a map method let arr = [1, 2, 3, 4, 5];

let mulArr = [];

arr.forEach(num => mulArr.push(num * 3));

> console.log(mulArr)

[3, 6, 9, 12, 15] -------------------------------------------- let arr = [1, 2, 3, 4, 5];

let mulArr = arr.map(num => num * 3);

> console.log(mulArr)

[3, 6, 9, 12, 15]



Thanks for reading my blog.

Happy coding!