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"];
const numbers = [1, 34, 23, 17, 10, 7];
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 }
];
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 },
]
*/
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"]
*/
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
*/
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}
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.
- Accumulator
- Current Value
- Current Index
- 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
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.
Top comments (21)
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.
Informative thanks for sharing ,timesindia.in provides all information related to IT Courses..
Awesome thank you ๐
Nice sharing!
Thank you so much ๐
How about .some()? :)
Also important. I will talk about more array methods in future posts. ๐๐ค
thx, this was helpful
Thank you. Glad you found it useful!
Wow! I understand nothing ๐
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
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 :)
Keep sharing!
Thank you. I will ๐
Some comments may only be visible to logged-in visitors. Sign in to view all comments.