Everything to know about Array Iteration Methods

Everything to know about Array Iteration Methods

Making Array Changes using Callback Functions

ยท

5 min read

Array Iterations are like tools inside of a toolbox labeled Array Changes. This toolbox holds different tools that will allow us (developers) to change or mutate our Javascript Arrays.

Javascript Array Iterators helps us iterate (to do over again, repeatedly, loop) through an array, manipulating each individual element in some way.

Array Iterators we want to learn and remember include: indexOf(), find(), filter(), map(), flatMap(), reduce(), reduceRight() and forEach().

Let's define these, while also exploring examples! You can work in Replit as you read through the examples, or wait until you get to the checklist in the end.

indexOf() ๐Ÿ”จ

This method or tool returns the index of the first occurrence of a stated value within an array or string. If this value is not found, it returns -1.

const pets = [{name: "Jorja"}, {name: "Cali"}, {name: "Walter-Raekwon"}];
const indexA = pets.findIndex(pet =>pet.name === "Jorja");
const indexB = pets.findIndex(pet =>pet.name === "Cali");
const indexC = pets.findIndex(pet =>pet.name === "Ryuk");
console.log(indexA); //Output: 0
console.log(indexB); //Output: 1
console.log(indexC); //Output: -1

We will use this example throughout the iterations for consistency. Here, I have listed my pets names in an array of objects (The brackets indicate its an array, the curly brackets indicate these are objects with the key value of name. To call the pets function, we use console.log(indexA);, putting the name of the pet inside the parentheses. The output will identify the array number. If we put a name that is not stated (a future pet name), we are given the value of -1. Note: IndexOf() looks a bit different here because our array is a group of objects.

find()๐Ÿ”ง

This method or tool returns the first element in an array that satisfies a provided testing function.

const pets = [{name: "Jorja"}, {name: "Cali"}, {name: "Walter-Raekwon"}];
const index = pets.find((index => index.name === 'Jorja'));
console.log(index); //Output: {name: 'Jorja'}

In our const pets example, we use the find() method to find the object with the name Jorja in our array. We then use a callback function, (index => index.name === 'Jorja') to check the name property of each object equal to "Jorja". The object will be returned if it is found, if not, it will return undefined.

filter()๐Ÿช›

This method or tool creates a new array with all of the elements that pass a test that is specified by a callback function.

const pets = [{name: "Jorja"}, {name: "Cali"}, {name: "Walter-Raekwon"}];
const filteredPets = pets.filter(pet => pet.name.length > 4);
console.log(filteredPets); // Output: [{name: "Jorja"}, {name: "Walter-Raekwon"}]

In this example, the filter() method iterates over each element (pet object) int he array and checks if the length of the name property is greater than 4. The pet objects fitting the description will be included and logged to the console .

map()๐Ÿชš

This method or tool creates a new array by applying a callback function to each element in the original array.

const pets = [{name: "Jorja"}, {name: "Cali"}, {name: "Walter-Raekwon"}];
const petNames = pets.map(pet => pet.name);
console.log(petNames); //Output: [ 'Jorja', 'Cali', 'Walter-Raekwon' ]

Here you can see a new array is created containing on the pet names. The callback function takes on each individual pet name as an argument and returns the specific property we want to extract.

flatMap()๐Ÿ—œ๏ธ

This method or tool used to transform and flatten nested arrays or arrays into a single array.

const pets = [{name: "Jorja"}, {name: "Cali"}, {name: "Walter-Raekwon"}];
const names = pets.flatMap(pet => pet.name);
console.log(names); //Output: ["Jorja", "Cali", "Walter-Raekwon"]

Like map(), flatMap() flattens the result into a new array. In this example, the flatMap() function is being used with an arrow function (pet => pet.name) to extract or pull the name property from each object in the pets array. The resulting array of names is stored in the name variable and then console-logged.

reduce()โ›๏ธ

This method or tool applies a callback function to reduce (or minimize) the array to a single value.

const pets = [{name: "Jorja"}, {name: "Cali"}, {name: "Walter-Raekwon"}];
const petsTogether = pets.reduce((accumulator, currentValue) => {
  return accumulator + currentValue.name + ', ';
}, '');
console.log(petsTogether);
// Output: "Jorja, Cali, Walter-Raekwon, "

In out example, the accumulator starts with an empty string ''. For each element in the pets array, the callback function concatenates the current pet's name with the accumulator, and returns the updated accumulator. See the pet names are now only separated by a common, but joined together.

reduceRight()๐Ÿช“

This method or tool is used to reduce an array to a single value from right to left. This is done by applying a function to each element of the array, starting from the rightmost element, and accumulates the result.

const pets = [{name: "Jorja"}, {name: "Cali"}, {name: "Walter-Raekwon"}];
const result = pets.reduceRight((accumulator, currentPet) => {
  return accumulator + " " + currentPet.name;
}, "");
console.log(result);
// Output: "Walter-Raekwon Cali Jorja"

Here we used reduceRight() to concatenate the names of the pets in reverse order. The initial value of the accumulator is an empty string (""). On each iteration, the current pet's name is added to the accumulator. Finally, the result is logged to the console.

***Note that reduceRight() works similarly to reduce(), but it starts from the last element and iterates towards the first element, whereas reduce() starts from the first element and iterates towards the last element.

forEach()๐Ÿ”ฉ

This method or tool iterates or loops over each element in an array and executes a callback function.

const pets = [{name: "Jorja"}, {name: "Cali"}, {name: "Walter-Raekwon"}];
pets.forEach((pet) => {
  console.log(pet.name);
});
//Output: 
//Jorja
//Cali
//Walter-Raekwon

The forEach() method loops through each element and prints the name property of each pet object.

๐Ÿ—’๏ธ Go through each method and paraphrase the definitions and use the examples above to create your own examples. Be sure to them in the Replit! If you want to add an additional layer, use a digital notebook such as Notion to save your code blocks in one place! I hope this has been helpful!

ย