DEV Community

Max
Max

Posted on

Array Iteration for Beginners

A Brief Review

Just about anything and everything can be represented by data. Some things are represented fairly easily on their own; for instance, the red color of an apple, my cat's age being 1 year old, or a character's catchphrase. In code, these can be represented by standalone variables:
let appleColor = 'red'
let mochiAge = 1
let buzzCatchphrase = 'To Infinity and Beyond'

Some data is best represented in pairs of keys and values. In this case, data is organized in what can be thought of as a dicitonary, where you look up the key or word and find the value or definition. This type of data structure in JavaScript is called an object. For a concrete example, we could store information about an employee in an object as follows:

let employee: {name: "John Smith", age: 32, title: "Office Manager"}

Data can also be represented as a list. Doing so may indicate a sort of relationship between variables or otherwise organize them as a collective. For example, the winning numbers of a lottery or a person's favorite movies. For these examples and many more, we use arrays. Arrays are a type of data structure; a way of associating and organizing information. The previous two examples can be represented as:

let winningNumbers = [02, 27, 42, 44, 51, 25]
let favoriteMovies = ['The Dark Knight Rises', 'Spirited Away', 'Stardust']

When using arrays, we often have to look through the array and interact with the items within it in a process called array iteration.

Array Iteration

.filter()

The filter method, as the name implies, will iterate through an array and remove, or filter, elements that do not meet a specified criteria. A simple example would be going through a list of numbers, and only keeping the numbers greater than 3 (filtering out numbers less than 3). Elements that meet the criteria will be returned in the form of an array.

The filter method takes a function as its argument (a callback function) and use it to determine what elements should be returned. This callback function is fed each element of the original array into it, and will return only the elements that meet the intended criteria.

The previous example could look something like this:
let list = [1,2,3,4,5]
function greaterThanThree(num){
return num > 3
}

list.filter(greaterThanThree(num)) // => [4,5]

Now let's look at a more complex example of .filter(). Suppose you had a watchlist app, similar to IMDB, where you have a list of movies and details about them including things like genre, leading actor, budget, etc. This data could be represented in an array of objects as follows:

let movies =
[{title: 'The Dark Knight', genre: 'superhero', star: 'Christian Bale'},
{title:'Captain America', genre: 'superhero', star: 'Chris Evans'},
{title: 'Snow Piercer', genre:'action', star: 'Chris Evans'},
{title: 'John Wick', genre: 'action', star: 'Keanu Reeves'}]

If we wanted to create a new array from this one to include only superhero movies, we would first create a function to be used as a callback in the .filter() method to check and return any movie in the superhero genre.

function superHeroes(movie){
return movie['genre'] === 'superhero'
}

Next we would invoke .filter() onto the movies array, passing the superHeroes function as an argument.

movies.filter(superHeroes)

Doing so will feed each individual element in the movies array into the superheroes function and then return a true or false based on the movie's genre. If the function returns true, it is added to an array that will be returned by the filter method.

movies.filter(superHeroes) // =>[{title: 'The Dark Knight', genre: 'superhero', star: 'Christian Bale'},
{title:'Captain America', genre: 'superhero', star: 'Chris Evans'}]

.map()

What if we wanted to modify every element in an array? For a simple example, suppose we had a list of numbers and we wanted to have a list of all those numbers doubled. In this case, we would use the .map() method. This method takes a callback function as an argument, and will create a new array that contains the original array elements modified by the callback funciton.

The above example could look something like this:
let numbers = [1,2,3,4]

function doubleNumbers (number){
return number * 2
}

numbers.map(doubleNumbers) // => [2,4,6,8]

As you can see, each number in the numbers array was passed to the doubleNumbers function as an argument, and then was returned as the value of itself times 2. These returned values were stored in a new array, and did not modify the original numbers array.

Just like with the filter method, lets explore a more complex example. Suppose you had an array of objects consisting of iconic characters and a phrase.

let characters = [{name: 'Woody', phrase: "You're my favorite deputy!"}, {name: 'Buzz', phrase: 'To infinity and beyond!'}, {name: 'Courage', phrase: 'The things I do for love.'}]

But instead of their catchphrases, you wanted to have the phrase be an introduction instead. First we need to write a function that will modify a character element and return the modified element.

function introduction(character){
character['phrase'] =
Hi, my name is ${character['name']}.
return character
}

Next we invoke the .map() iterator on the characters array, and pass it our introduction callback function, and it should return an array with the modified phrases.

character.map(introduction) // =>[{name: 'Woody', phrase: 'Hi, my name is Woody.'}, {name: 'Buzz', phrase: 'Hi, my name is Buzz.'},{name: 'Courage', phrase: 'Hi, my name is Courage.'}]

Summary

There are more iterator methods for arrays than the two covered in this post. And each one provides a different way to interact with the elements in the array to achieve a goal. Hopefully with these two examples, you have gained a basic understanding of array iteration, callback functions, and how imporant of tools these concepts are for any coding project.

Discussion (4)

Collapse
frankwisniewski profile image
Frank Wisniewski

we are in the year 2022!!

const greaterThanThree = num => num > 3
Enter fullscreen mode Exit fullscreen mode
Collapse
fjones profile image
FJones

To be fair (despite the formatting), it does say "for beginners", and the prevailing thought is still that beginners don't like arrow functions.

That said, if we want to do this, might as well do it right:

const greaterThan = than => num => num > than;
const greaterThanThree = greaterThan(3);
Enter fullscreen mode Exit fullscreen mode
Collapse
frankwisniewski profile image
Frank Wisniewski

Well then I'd rather do it that way

const isGreaterThan = num => value => value > num
let list = [1,2,3,4,5]    
console.log(
  list.filter(isGreaterThan(3)) 
)
Enter fullscreen mode Exit fullscreen mode
Collapse
phamphong profile image
phamphong

let list = [1,2,3,4,5]
function greaterThanThree(num){
return num > 3
}
list.filter(greaterThanThree) // => [4,5]