DEV Community

loading...
Cover image for 5 important JavaScript array methods

5 important JavaScript array methods

marlonry profile image marlonry Updated on ・3 min read

Arrays are a crucial part of any programming language. Arrays are commonly used on a daily basis in any type of project and knowing how to interact with arrays will make your journey more enjoyable.

Before talking about the Array methods, first, let's understand what an Array is:

Arrays are a data structure that can store any type of data. These can contain a combination of elements, such as strings, numbers, or boolean values. For example an array of movie names or an array of numbers as shown on the example below:

const films = ["Harry Potter", "Tenet", "Mulan", "Wonder Woman"];
Enter fullscreen mode Exit fullscreen mode
const numbers = [1, 34, 23, 17, 10, 7];
Enter fullscreen mode Exit fullscreen mode

Now that we know what Arrays are, we can move on to talk about some Array methods that are really important.

For the examples below, I will be using the following Array of objects to illustrate the different Array methods. The Array contains various information about movies, such as name, year, and rating as shown below.

const films = [
  { name: "Tenet", year: 2020, rating: 7.5 },
  { name: "Wonder Woman 1984", year: 2020, rating: 5.4 },
  { name: "The Karate Kid", year: 1984, rating: 7.3 },
  { name: "Avengers: Endgame", year: 2019, rating: 8.4 },
  { name: "The Godfather", year: 1972, rating: 9.2 },
  { name: "Godzilla", year: 2014, rating: 6.4 },
  { name: "The Croods: A New Age", year: 2020, rating: 7.0 }
];
Enter fullscreen mode Exit fullscreen mode

Filter

As the name indicates, the filter method can be used to filter or extract any type of information from an array based on a condition. This returns or creates a new array with the filtered items. In the following example, we get all the films that were released before the year 2000.

const filteredFilms = films.filter(film => {
  return film.year < 2000; // condition
});

/*
Output: filteredFilms = [
  { name: "The Karate Kid", year: 1984, rating: 7.3 },
  { name: "The Godfather", year: 1972, rating: 9.2 },
]
*/
Enter fullscreen mode Exit fullscreen mode

Map

The Map method allows you to iterate through all the items in the array to carry out a specific task based on the provided function. Map will also create a new array with the results. In the following example, we are getting the names of all the films.

const filmNames = films.map((film) => {
  return film.name;
});

/*
Output: ["Tenet", "Wonder Woman 1984", "The Karate Kid", 
"Avengers: Endgame", "The Godfather", "Godzilla", 
"The Croods: A New Age"]
*/
Enter fullscreen mode Exit fullscreen mode

ForEach

The Foreach method also allows us to iterate through all the items in an array but the difference is that it won't create any new array but rather it will execute the provided function on each item. In the following example, we are displaying on the console, a string with the name of the film and its rating.

films.forEach((film) => {
  console.log(`${film.name} has a rating of ${film.rating}`);
});

/*
Output: Tenet has a rating of 7.5 
Wonder Woman 1984 has a rating of 5.4 
The Karate Kid has a rating of 7.3 
Avengers: Endgame has a rating of 8.4 
The Godfather has a rating of 9.2 
Godzilla has a rating of 6.4 
The Croods: A New Age has a rating of 7 
*/
Enter fullscreen mode Exit fullscreen mode

Find

The find method returns the first item on the array that passes the condition on the provided function. In the case that there are no items that satisfy the condition, it will simply return "undefined". In the following example, we are passing a testing function to find the name of a film.

const foundFilm = films.find((film) => {
  return film.name === "Avengers: Endgame"; //condition
});

// Output: {name: "Avengers: Endgame", year: 2019, rating: 8.4}
Enter fullscreen mode Exit fullscreen mode

Reduce

And finally, we have the reduce method which is a bit confusing to understand. It allows us to iterate every item in the array and combine everything into a single result by passing a reducer function and an optional initial value. This reducer function takes 4 different arguments.

  1. Accumulator
  2. Current Value
  3. Current Index
  4. Source Array

The arguments that were are going to worry about for now are the accumulator (which is the current total on each iteration) and the current value (which gives you access to the current item on each iteration).

In the following example, we are passing a reducer function that adds the ratings of each film and an initial value of 0, and then display the average on the console.

const total = films.reduce((currentTotal, currentValue) => {
  return currentTotal + currentValue.rating;
}, 0);

// total = 51.199999999999996

console.log(total / films.length); // 7.314285714285714
Enter fullscreen mode Exit fullscreen mode

That's it for me today. Thank you for reading my first DEV blog post. I will keep posting more content related to web development, programming, and things I've learned. Happy coding! 😃 catch you in the next one.

Discussion (21)

pic
Editor guide
Collapse
angelomiranda profile image
angelo.miranda • Edited

Nice Marlonry,

Array is one my favorite data structure. As a matter of fact, i just created a youtube video of array map and released it today :D Nice of you to help out the community.

Collapse
timesindia_in profile image
timesindia.in

Informative thanks for sharing ,timesindia.in provides all information related to IT Courses..

Collapse
marlonry profile image
marlonry Author

Awesome thank you 😁

Collapse
oscarwang913 profile image
Rui Sheng Wang (Oscar)

Nice sharing!

Collapse
marlonry profile image
marlonry Author

Thank you so much 😁

Collapse
eugenman profile image
Eugen

How about .some()? :)

Collapse
marlonry profile image
marlonry Author

Also important. I will talk about more array methods in future posts. 😀🤙

Collapse
pretty123dian profile image
Pretty Diane

thx, this was helpful

Collapse
marlonry profile image
marlonry Author

Thank you. Glad you found it useful!

Collapse
cr11mob profile image
CR11-Mob

Wow! I understand nothing 😅

Collapse
weironiottan profile image
Christian Gabrielsson

Awesome!

Although I would add .includes() for filtering and .flatmap(), I started using this more and more with Observables when I want to flat and map an observable

Collapse
marlonry profile image
marlonry Author

Yeah definitely those methods are also useful for some use cases. I'll be talking about some more important methods in future posts. Thank you for you input :)

Collapse
aalphaindia profile image
Pawan Pawar

Keep sharing!

Collapse
marlonry profile image
marlonry Author

Thank you. I will 😊

Collapse
paul_mountney_24e4867f3d3 profile image
Paul Mountney

I'm a total noob to this programming gig. I typed in my own version of the array you suggested here. Now i'd like to know where to type in the other bits of code to get the results similar to what you got. What console do you use? where can i get it?

Collapse
marlonry profile image
marlonry Author

We've all been there. You need to console.log() the name of the variable and then you'll see what has been returned. let me know how it goes :D. don't give up.

Collapse
paul_mountney_24e4867f3d3 profile image
Paul Mountney

The variable name is: filteredBooks, so i put that in the console log like you suggested, console.log(filteredBooks), hit enter and i got a bunch of error messages. What am i doing wrong?

Thread Thread
marlonry profile image
marlonry Author

😅 I would have to see the code to be able to help you.

Thread Thread
paul_mountney_24e4867f3d3 profile image
Paul Mountney

I figured it out, i was supposed to put the code:
const filteredBooks = books.filter(books => {
return books.writer === "Jeremiah";
});

console.log(filteredBooks)

at the end of my array, and i ran it through Nodejs

Thread Thread
marlonry profile image
marlonry Author

Awesome. Glad you got it!

Collapse
marraybob profile image
Bob Marray

Wow! I understand nothing