Navigating the Grand Line of Array Iteration

A Cheat Sheet to JavaScript’s Array Iteration Methods

Evan Roberts
10 min readApr 23, 2023

Since I started learning JavaScript, there has been one concept that I’ve always struggled to get a grasp of… Array Iteration. No matter how much I worked with these methods I seemingly still lacked an understanding of each and felt quite overwhelmed by the variety. The goal of this blog / cheat sheet is to act as an all in one resource for myself and other developers like me who struggle in their understanding of Array Iteration, providing a breakdown of each as well as examples using one of the greatest Shōnen of all time ‘One Piece’.

Monkey D. Luffy looking braindead
Mfw trying to understand Array Iteration

Table of Contents
· What is Array Iteration?
· forEach()
· map()
· filter()
· reduce()
· every()
· some()
· find()
· findIndex()
· entries()
· keys()
· values()

What is Array Iteration?

Array iteration is the process of looping through each and every element within an array and performing an action, usually a function, on each of those elements. Whether it be to manipulate, transform, or analyze that data, this fundamental concept and its many methods is a must have in every developers skill set.

forEach():

Executes a provided function once for each array element

Return Value: undefined

Syntax:

array.forEach(function(currentValue, index, array) {
// function code here
})

Parameters:

function: (Required) The function that will execute on each element in your array

currentValue: (Required) The value of the current element in the array being processed

index: (Optional) The index of the current element in the array being processed

array: (Optional) The array being processed

Example:

const strawHats = ['Luffy', 'Zoro', 'Nami', 'Usopp', 'Sanji', 'Chopper', 'Robin', 'Franky', 'Brook', 'Jinbe']

strawHats.forEach(strawHat => {
console.log(strawHat)
})

//Returns:
Luffy
Zoro
Nami
Usopp
Sanji
Chopper
Robin
Franky
Brook
Jinbe

In this example we use the forEach() method on the ‘strawHats’ array to iterate over each element in the array. An anonymous arrow function (=>) is passed as the callback function to be executed each element. Within the body is console.log() which will log each element of the array into your console.

map():

Creates a new array with the results of calling a provided function on every element in the original array.

Return value: a new array with the same length as the original, where each element is the result of the function

Syntax:

const newArray = array.map(function(currentValue, index, array) {
// function code here
})

Parameters:

function: (Required) A function to be executed for each element in the array

currentValue: (Required) The value of the current element being processed

index: (Optional) The index of the current element being processed

array: (Optional) The array being processed

Example:

const strawHats = ['Luffy', 'Zoro', 'Nami', 'Usopp', 'Sanji', 'Chopper', 'Robin', 'Franky', 'Brook', 'Jinbe']

const upperCaseStrawHats = strawHats.map(strawHat => strawHat.toUpperCase());

// Returns:
['LUFFY', 'ZORO', 'NAMI', 'USOPP', 'SANJI', 'CHOPPER', 'ROBIN', 'FRANKY', 'BROOK', 'JINBE']

In this example, our objective to to return a new array where each element in our strawHats array is now capitalized and assign it to our declared variable ‘upperCaseStrawHats’. Using the .map() method we can iterate over each element in our array and apply the .toUpperCase() function to each. The result of this is a new array assigned to our newly declared variable where each element of the previous has been capitalized.

filter():

Return Value: A new array with all elements that pass the function’s test

Syntax:

const newArray = array.filter(function(currentValue, index, array) {
// function code here
})

Parameters:

function: (Required) A function to be executed for each element in the array

currentValue: (Required) The value of the current element being processed

index: (Optional) The index of the current element being processed

array: (Optional) The array being processed

Example:

const strawHats = ['Luffy', 'Zoro', 'Nami', 'Usopp', 'Sanji', 'Chopper', 'Robin', 'Franky', 'Brook', 'Jinbe']

const filteredStrawHats = strawHats.filter(strawHat => strawHat.length <= 4)

console.log(filteredStrawHats)

// Returns:
['Zoro', 'Nami']

In this example, we define a new variable ‘filteredStrawHats’, and set it equal to the result of our .filter() method on our strawHats array. The .filter() method is passed in ‘strawHat’ to represent each element within our array, and an arrow function (=>) which checks whether or not the length of each element is less than or equal to 4. The elements that fit this condition will be returned in a new array and assigned to our ‘filteredStrawHats’ variable

reduce():

Executes a reducer function on each element of the array

Return Value: A single output value that is a result of the function on each element

Syntax:

const result = array.reduce(function(accumulator, currentValue, index, array) {
// function code here
}, initialValue)

Parameters:

function: (Required) A function to be executed for each element in the array

accumulator: (Required) A value to be used as the first argument in the first call to the function and is used to accumulate the result.

currentValue: (Required) The value of the current element being processed

index: (Optional) The index of the current element being processed

array: (Optional) The array being processed

initialValue: (Optional) A value to be used as the initial value of the accumulator

Example:

const strawHats = [
{ name: 'Luffy', bounty: 3000000000 },
{ name: 'Zoro', bounty: 1111000000 },
{ name: 'Nami', bounty: 366000000 },
{ name: 'Usopp', bounty: 500000000 },
{ name: 'Sanji', bounty: 1032000000 },
{ name: 'Chopper', bounty: 1000 },
{ name: 'Robin', bounty: 930000000 },
{ name: 'Franky', bounty: 394000000 },
{ name: 'Brook', bounty: 383000000 },
{ name: 'Jinbe', bounty: 1100000000 }
];

const totalBounty = strawHats.reduce((acc, curr) => acc + curr.bounty, 0);

console.log(`The Straw Hats total bounty is ${totalBounty} berries`)

// Returns:
The Straw Hats total bounty is 8816001000 berries

In this example we have our ‘strawHats’ array, which contains an object for each crew member with key and value pairs of their names, and bounty. We then declare a new variable ‘totalBounty’ and set it equal to the result of our following .reduce() method. Within our .reduce() method, we pass an arrow function (=>) as our callback function that takes in two arguments, the accumulator (acc) and the currentValue (curr) of the array. In this instance we use ‘acc + curr.bounty’ to add the ‘bounty’ property of each member to the accumulator value, we then have our initialValue set to 0. The result of the method is then assigned to the ‘totalBounty’ variable.

every():

Tests whether all of the elements in the array pass the test within the function

Return Value: A boolean value (true or false)

Syntax:

const result = array.every(function(currentValue, index, array) {
// function code here
})

Parameters:

function: (Required) A function to be executed for each element in the array

currentValue: (Required) The value of the current element being processed

index: (Optional) The index of the current element being processed

array: (Optional) The array being processed

Example:

const strawHats = [
{ name: 'Luffy', bounty: 3000000000 },
{ name: 'Zoro', bounty: 1111000000 },
{ name: 'Nami', bounty: 366000000 },
{ name: 'Usopp', bounty: 500000000 },
{ name: 'Sanji', bounty: 1032000000 },
{ name: 'Chopper', bounty: 1000 },
{ name: 'Robin', bounty: 930000000 },
{ name: 'Franky', bounty: 394000000 },
{ name: 'Brook', bounty: 383000000 },
{ name: 'Jinbe', bounty: 1100000000 }
];

const allHaveBounties = strawHats.every(member => member.bounty > 0);

console.log(allHaveBounties)

// Returns:
true

In this example we have our ‘strawHats’ array, which contains an object for each crew member with key and value pairs of their names, and bounty. We use the .every() method on this array to check if every crew member has a bounty and assign the result to a variable called ‘allHaveBounties’. We pass in an arrow function (=>) with the parameter ‘member’ to signify each object within our array. The body of the function then checks if ‘member.bounty’ is greater than 0 and returns a boolean value as a result, in this case it returns ‘true’.

some():

Tests if at least one element in the array passes the test within the function

Return Value: A boolean value (true or false)

Syntax:

const result = array.some(function(currentValue, index, array) {
// function code here
});

Parameters:

function: (Required) A function to be executed for each element in the array

currentValue: (Required) The value of the current element being processed

index: (Optional) The index of the current element being processed

array: (Optional) The array being processed

Example:

const strawHats = [
{ name: 'Luffy', bounty: 3000000000 },
{ name: 'Zoro', bounty: 1111000000 },
{ name: 'Nami', bounty: 366000000 },
{ name: 'Usopp', bounty: 500000000 },
{ name: 'Sanji', bounty: 1032000000 },
{ name: 'Chopper', bounty: 1000 },
{ name: 'Robin', bounty: 930000000 },
{ name: 'Franky', bounty: 394000000 },
{ name: 'Brook', bounty: 383000000 },
{ name: 'Jinbe', bounty: 1100000000 }
];

const bountyUnderOneMillion = strawHats.some(member => member.bounty <= 1000000)

console.log(bountyUnderOneMillion)

// Returns:
true

In this example we have our ‘strawHats’ array, which contains an object for each crew member with key and value pairs of their names, and bounty. We use the .some() method to check if any member has a bounty value less than or equal to one million and assign the return value to a new variable ‘bountyUnderOneMillion’. We pass in an arrow function (=>) with the parameter ‘member’ which signifies each object within our array. The body of the function checks if the ‘member.bounty’ is greater than or equal to one million and returns a boolean value, in this case it returns ‘true’.

find():

Return Value: The first matching element in the array, or undefined if there is no match

Syntax:

const result = array.find(function(currentValue, index, array) {
// function code here
});

Parameters:

function: (Required) A function to be executed for each element in the array

currentValue: (Required) The value of the current element being processed

index: (Optional) The index of the current element being processed

array: (Optional) The array being processed

Example:

const strawHats = [
{ name: 'Luffy', bounty: 3000000000 },
{ name: 'Zoro', bounty: 1111000000 },
{ name: 'Nami', bounty: 366000000 },
{ name: 'Usopp', bounty: 500000000 },
{ name: 'Sanji', bounty: 1032000000 },
{ name: 'Chopper', bounty: 1000 },
{ name: 'Robin', bounty: 930000000 },
{ name: 'Franky', bounty: 394000000 },
{ name: 'Brook', bounty: 383000000 },
{ name: 'Jinbe', bounty: 1100000000 }
];

const foundMember = strawHats.find(member => member.name === 'Luffy');

console.log(foundMember);

// Returns:
{ name: 'Luffy', bounty: 3000000000 }

In this example we have our ‘strawHats’ array, which contains an object for each crew member with key and value pairs of their names, and bounty. The .find() method is used to iterate over the ‘strawHats’ array to find the member that is equal to ‘Luffy’. The function checks the ‘.name’ property of the current iterating member and checks if it is strictly equal (===) and if it is, it will return that object and assign it to the ‘foundMember’ variable.

findIndex():

Return Value: The index value of the first matching element in the array, or -1 if there is no match

Syntax:

const result = array.findIndex(function(currentValue, index, array) {
// function code here
});

Parameters:

function: (Required) A function to be executed for each element in the array

currentValue: (Required) The value of the current element being processed

index: (Optional) The index of the current element being processed

array: (Optional) The array being processed

Example:

const strawHats = [
{ name: 'Luffy', bounty: 3000000000 },
{ name: 'Zoro', bounty: 1111000000 },
{ name: 'Nami', bounty: 366000000 },
{ name: 'Usopp', bounty: 500000000 },
{ name: 'Sanji', bounty: 1032000000 },
{ name: 'Chopper', bounty: 1000 },
{ name: 'Robin', bounty: 930000000 },
{ name: 'Franky', bounty: 394000000 },
{ name: 'Brook', bounty: 383000000 },
{ name: 'Jinbe', bounty: 1100000000 }
];

const foundMember = strawHats.findIndex(member => member.name === 'Franky');

console.log(foundMember);

// Returns:
7

In this example we have our ‘strawHats’ array, which contains an object for each crew member with key and value pairs of their names, and bounty. The .findIndex() method is used to iterate over each object in the ‘strawHats’ array and checks if the .name property of the current object is strictly equal to ‘Franky’. If an object returns true, that object’s index in the array will be assigned to the ‘foundMember’ variable. In this case, it will be true and return the index of ‘7’.

entries():

Return Value: A new array iterator object that contains an array of

[index, element] pairs.

Syntax:

const iterator = array.entries();

Parameters:

None

Example:

const strawHats = [
{ name: 'Luffy', bounty: 3000000000 },
{ name: 'Zoro', bounty: 1111000000 },
{ name: 'Nami', bounty: 366000000 },
{ name: 'Usopp', bounty: 500000000 },
{ name: 'Sanji', bounty: 1032000000 },
{ name: 'Chopper', bounty: 1000 },
{ name: 'Robin', bounty: 930000000 },
{ name: 'Franky', bounty: 394000000 },
{ name: 'Brook', bounty: 383000000 },
{ name: 'Jinbe', bounty: 1100000000 }
];

for (const [index, { name, bounty }] of strawHats.entries()) {
console.log(`#${index+1}: ${name} - ${bounty} berries bounty`);
}

// Returns:
#1: Luffy - 3000000000 berries bounty
#2: Zoro - 1111000000 berries bounty
#3: Nami - 366000000 berries bounty
#4: Usopp - 500000000 berries bounty
#5: Sanji - 1032000000 berries bounty
#6: Chopper - 1000 berries bounty
#7: Robin - 930000000 berries bounty
#8: Franky - 394000000 berries bounty
#9: Brook - 383000000 berries bounty
#10: Jinbe - 1100000000 berries bounty

In this example we have our ‘strawHats’ array, which contains an object for each crew member with key and value pairs of their names, and bounty. We use the .entries() method to iterate over the ‘strawHats’ array, in which a ‘for…of’ loop will destructure each object of the array into 3 variables, ‘index’, ‘name’, and ‘bounty’. Inside of the loop, we have a console.log() which outputs the name and bounty of each member along with their index value + 1 as a formatted string. This serves as a useful way of displaying information about our objects.

keys():

Return Value: A new array iterator operator object that contains the keys of each index in the array

Syntax:

const iterator = array.keys();

Parameters:

None

Example:

const strawHats = [ 
{captain: 'Luffy'},
{swordsman: 'Zoro'},
{navigator: 'Nami'},
{sniper: 'Usopp'},
{cook: 'Sanji'},
{doctor: 'Chopper'},
{archaeologist: 'Robin'},
{shipwright: 'Franky'},
{musician: 'Brook'},
{helmsman: 'Jinbe'}
];

const role = Object.keys(strawHats[0]);

console.log(role);

// Returns:
['captain']

In this example, we have the ‘strawHats’ array that contains objects with keys of the crew roles and the values set as the crew member who fits that role. We then use the Object.keys() method to extract the key of the first object in the array and assign the results to a new array named ‘role’.

values():

Return Value: A new array iterator object that contains the values of each index in the array

Syntax:

const iterator = array.values();

Parameters:

None

Example:

const strawHats = [
{ name: 'Luffy', bounty: 3000000000 },
{ name: 'Zoro', bounty: 1111000000 },
{ name: 'Nami', bounty: 366000000 },
{ name: 'Usopp', bounty: 500000000 },
{ name: 'Sanji', bounty: 1032000000 },
{ name: 'Chopper', bounty: 1000 },
{ name: 'Robin', bounty: 930000000 },
{ name: 'Franky', bounty: 394000000 },
{ name: 'Brook', bounty: 383000000 },
{ name: 'Jinbe', bounty: 1100000000 }
];

const bounties = Object.values(strawHats).map(member => member.bounty);

console.log(bounties);

// Returns:
[3000000000, 1111000000, 366000000, 500000000, 1032000000, 1000, 930000000, 394000000, 383000000, 1100000000]

In this example, we have an object ‘strawHats’ that contains objects with for each crew member with key and value pairs for their names and bounties. The .values() method is used to return an iterator of the bounty values, and then chains into a .map() to turn this into a new array which is assigned to the variable ‘bounties’.

References:

Duckett, Jon, et al. JavaScript & JQuery. Wiley, 2015.

MDN Web Docs, https://developer.mozilla.org/en-US/.

JavaScript Array Reference, https://www.w3schools.com/jsref/jsref_obj_array.asp.

--

--