Originally posted on my blog
In JavaScript, an array is a special variable that is used to store different elements. It has some built-in properties and methods we can use to add, remove, iterate, or manipulate data following our needs. And knowing JavaScript array methods can lift your skills as a developer.
In this post, we're going to see 15 array methods that can help you manipulate your data properly.
- 1. some()
- 2. reduce()
- 3. every()
- 4. map()
- 5. flat()
- 6. filter()
- 7. forEach()
- 8. findIndex()
- 9. find()
- 10. sort()
- 11. concat()
- 12. fill()
- 13. includes()
- 14. reverse()
- 15. flatMap()
Notice that mostly in this post, we'll simplify the function passed as parameter.
// Instead of using this way
myAwesomeArray.some(test => {
if (test === "d") {
return test
}
})
// We'll use the shorter one
myAwesomeArray.some(test => test === "d")
1. some()
This method tests the array with a function passed as a parameter. It will return true
if at least one element matches the test and false
for the opposite.
const myAwesomeArray = ["a", "b", "c", "d", "e"]
myAwesomeArray.some(test => test === "d")
//-------> Output : true
2. reduce()
This method receives a function which has an accumulator and a value as an argument. It applies the function to the accumulator and each value in the array to return at the end just a single value.
const myAwesomeArray = [1, 2, 3, 4, 5]
myAwesomeArray.reduce((total, value) => total * value)
// 1 * 2 * 3 * 4 * 5
//-------> Output = 120
3. every()
This method tests the array with a function passed as a parameter. It will return true
if each element of the array match the test and false
for the opposite.
const myAwesomeArray = ["a", "b", "c", "d", "e"]
myAwesomeArray.every(test => test === "d")
//-------> Output : false
const myAwesomeArray2 = ["a", "a", "a", "a", "a"]
myAwesomeArray2.every(test => test === "a")
//-------> Output : true
4. map()
This method receives a function as a parameter. And return a new array that contains an image of each element of the array. It will always return the same amount of items.
const myAwesomeArray = [5, 4, 3, 2, 1]
myAwesomeArray.map(x => x * x)
//-------> Output : 25
// 16
// 9
// 4
// 1
5. flat()
This method creates a new array that contains the elements holden on the sub-array and flat it into the new array. Notice that, this method will go only one level depth.
const myAwesomeArray = [[1, 2], [3, 4], 5]
myAwesomeArray.flat()
//-------> Output : [1, 2, 3, 4, 5]
6. filter()
This method receives a function as a parameter. And return a new array that contains all the elements of the array for which the filtering function passed as argument returns true
.
const myAwesomeArray = [
{ id: 1, name: "john" },
{ id: 2, name: "Ali" },
{ id: 3, name: "Mass" },
{ id: 4, name: "Mass" },
]
myAwesomeArray.filter(element => element.name === "Mass")
//-------> Output : 0:{id: 3, name: "Mass"},
// 1:{id: 4, name: "Mass"}
7. forEach()
This method applies a function to each element of the array.
const myAwesomeArray = [
{ id: 1, name: "john" },
{ id: 2, name: "Ali" },
{ id: 3, name: "Mass" },
]
myAwesomeArray.forEach(element => console.log(element.name))
//-------> Output : john
// Ali
// Mass
8. findIndex()
This method receives a function as a parameter and will apply it to the array. It returns the index of an element found and which satisfies the test function passed as an argument or -1
if none satisfies it.
const myAwesomeArray = [
{ id: 1, name: "john" },
{ id: 2, name: "Ali" },
{ id: 3, name: "Mass" },
]
myAwesomeArray.findIndex(element => element.id === 3)
//-------> Output : 2
myAwesomeArray.findIndex(element => element.id === 7)
//-------> Output : -1
9. find()
This method receives a function as an argument and will apply it to the array. It returns the value of an element found in the array and which satisfies the test function. Otherwise, it returns undefined
.
const myAwesomeArray = [
{ id: 1, name: "john" },
{ id: 2, name: "Ali" },
{ id: 3, name: "Mass" },
]
myAwesomeArray.find(element => element.id === 3)
//-------> Output : {id: 3, name: "Mass"}
myAwesomeArray.find(element => element.id === 7)
//-------> Output : undefined
10. sort()
This method receives a function as a parameter. It sorts the elements of an array and returns it.
const myAwesomeArray = [5, 4, 3, 2, 1]
// Sort from smallest to largest
myAwesomeArray.sort((a, b) => a - b)
//-------> Output : [1, 2, 3, 4, 5]
// Sort from largest to smallest
myAwesomeArray.sort((a, b) => b - a)
//-------> Output : [5, 4, 3, 2, 1]
11. concat()
This method will merge two or more arrays/values by concatenating it. It returns a new array with the elements.
const myAwesomeArray = [1, 2, 3, 4, 5]
const myAwesomeArray2 = [10, 20, 30, 40, 50]
myAwesomeArray.concat(myAwesomeArray2)
//-------> Output : [1, 2, 3, 4, 5, 10, 20, 30, 40, 50]
12. fill()
This method fills all the elements of a given array with the same value, from a start index (default 0) to an end index (default array.length).
const myAwesomeArray = [1, 2, 3, 4, 5]
// The first argument (0) is the value
// The second argument (1) is the starting index
// The third argument (3) is the ending index
myAwesomeArray.fill(0, 1, 3)
//-------> Output : [1, 0, 0, 4, 5]
13. includes()
This method will return true
if the array contains a certain element, and false
if not.
const myAwesomeArray = [1, 2, 3, 4, 5]
myAwesomeArray.includes(3)
//-------> Output : true
myAwesomeArray.includes(8)
//-------> Output : false
14. reverse()
This method reverses an array. The first element becomes the last, and the last element will be the first.
const myAwesomeArray = ["e", "d", "c", "b", "a"]
myAwesomeArray.reverse()
//-------> Output : ['a', 'b', 'c', 'd', 'e']
15. flatMap()
The method applies a function to each element of the array and then flatten the result into an array. It combines flat()
and map()
in one function.
const myAwesomeArray = [[1], [2], [3], [4], [5]]
myAwesomeArray.flatMap(arr => arr * 10)
//-------> Output : [10, 20, 30, 40, 50]
// With .flat() and .map()
myAwesomeArray.flat().map(arr => arr * 10)
//-------> Output : [10, 20, 30, 40, 50]
Discussion (72)
This post could be called just "15 must-know JavaScript array methods". No need the "in 2020".
I don't think these methods were really necessary in 2019, but now? Can't do without them.
I'd say they were necessary in 2018 and possibly even earlier. All these "in 2020" articles are clickbait in my opinion.
This is your opinion, and I fully respect it. However, I've added "in 2020", to just make this article easy to find for beginners. And also knowing these methods is relevant for 2020, in my opinion, because most of them introduce you to functional programming.
I see that I tend to click more on articles which have "in 2020" in the title so I guess it works since this is what I googled for :)
@idan haha that is brilliant response.
I totally agree. We hear more and more functional programming in JavaScript world. And using some of these methods makes sense because they manipulate the array in an immutable way.
I think "in 2020" is more fun. No, I'm kidding. I will update the title next week to not limit it in "2020" only. Thanks for your comment
Leave it. It helps with the SEO and, if anything, it will show first for beginners when they search for it. It's an important article and the 2020 really doesn't hurt anyone
So, I'll let the title as it is.
I personally like
includes()
for transforming a code likeif (value === 1 || value === 2 || value === 3) {...}
into
if ([1, 2, 3].includes(value)) {...}
It's a very handy method.
I think everyone know
.push()
, but recently I need.shift()
.I think I might not need double-ended dequeue, yet.
The most important things you should emphasize, IMO, are,
Some other should-know, I think, are
Great feedback. I will do a post on it later. Thanks again :).
Nice article.
But I am confused what is the difference between map and forEach? Output looks the same.
map
andforEach
technically they do the same job. They both iterate your data holden in a given array. But under the hood they are different.map
instead of manipulating the array directly, it will return a new array that contains an image of each element of the array. In the case offorEach
, it will manipulate the array directly. That's the difference.The example is not particularly well chosen.
map
is about data transformation, so using it for a side-effect likeconsole.log
leads to confusion.Something like the following would maybe better illustrate the point:
Even with your example, it will be not that clear. I think the difference is made by the definition. But anyway, I will update the code with your example. Thanks
It's at least clearer that the intent of
map
is returning an array with modified data, not performing an action on each element.I totally agree. I've updated the example with yours. Thanks again for your suggestion.
Thanks. Got it now)
map()
takes a function as argument which will run on all elements on the array (getting a transformed value), and then return a new array with all transformed values.If we run the following array through
.map(x => x + 1)
we get:forEach()
will just iterate on the array. Its return value isundefined
.Neither function will mutate the original array.
Great explanations and examples. Thanks again
Greatly appreciate your effort for creating this list. It allowed me to get a stronger grasp on the language.
I would like to mention that during my research of these methods you've brought to all of our attention, I found that the
flat()
method takes an argument for the depth, so while you are correct thatmyArr.flat()
will default to a depth of one, it's also possible to specify larger values, and even include an infinite option.For example (stolen directly from the MDN web docs):
There is one issue with the 2nd example used in the flatmap. The .flat() call at the end isn't needed, if you run the following code you will see that it evaluates to true
The issue is that if you execute
[1] * 10
it will return10
and not[10]
as you would expectThere is no issue with that code. It's just two examples.
The first is used with
flatMap()
And the second uses
flat()
andmap()
.As a side note, with
flatMap()
, themap()
function is applied first andflat()
comes after.Hi there, great article thanks!
I think you forgot about another method, which is similar to
reduce
: reduceRight.It's a handy method, but it's very similar to reduce except that reduceRight() start reducing the array from the right to the left. And for the case of reduce(), it starts from left to right. Thanks for your comment
Great article, love that every single one of them is to the point and clear.
One small typo to fix is for Number 13 (Includes), the output should be "true".
Sorry, for the mistyping. Now it's good :). Thanks again for reading it
Awesome post, thank you :). Just a curious question (junior dev), should we avoid using
forEach()
because it'll mutate the data?forEach()
is not bad, it's not like DON'T USE IT. But it depends on the use case.If you tend to functional programming, immutability and all that kind of stuff, you should use
map()
more often thanforEach()
.forEach
is preferable when you're planning to do something like logging out your data or save the data to a database. But don't change your data withforEach
.Instead, use
map()
when you plan to change or alternate your data. You can even usefilter()
,sort()
,reduce()
etc. in conjunction withmap()
. You can still do the same thing withforEach()
, but it's preferable to usemap()
because it manipulates your data in an immutable way.Some folks also say that
map()
is faster thanforEach()
regarding performance.However, in the end, It depends on what you’re trying to accomplish.
Awesome, thank you for the detailed response :)
Last one is wrong, myAwesomeArray.map(arr => arr * 10).flat()
It should be
myAwesomeArray.flat().map(arr => arr * 10)
It's not wrong. I've just followed the way
flatMap()
work. It appliesmap()
first andflat()
after. Therefore for the example offlat()
andmap()
i used the same method. But if you want too you can flat the array first.Try it in JSFiddler, Chrome, it does not work, it is wrong !!
I've not tested with your array. You're right. Thanks for your comment.
Sorry, but NOW it's incorrect - it was correct before. That's beacuse the flat part in flatMap() works differently, than .flat(1) alone, it only works for [[1], [2]], but not for [[1, 2]].
See? flatMap will put the NaN there as well, try it for yourself.
I'd say it's either a bug in the implementation or on MDN description:
and later:
Example on MDN:
Which translates to this one-liner:
and not the other way around:
Some note towards C# people who look at this and think it's the same as LINQ. It is not, as most of these methods create a new array as a result. Usually it doesn't matter as much, but consider what happens if the array is very large and you first map it to some complex and heavy calculation and only then you filter it. It may seem obvious, but only if you actually think about it, which to my shame I only did recently.
Also, shameless plus for my own library that uses ES6 iterators/generators to emulate LINQ in Javascript: siderite.dev/blog/linq-in-javascri... ;)
Love it, please provide a place where we can go to practice all these skills.
I'm glad you like it. Maybe I'll create a github repo for that.
Appreciate it or you can just edit it and point a known resource to practice each.
Why about "flat()" -> "Notice that, this method will go only one level depth."?
On MDN - "The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.".
Nice.
The output for 13 (includes) is wrong (copy/paste demon :)).
Sorry, It's just a mistyping. Now it's good :)
Thanks again.
If I had $10 for each time something like that happened to me, I could buy my own country! :D
:) for sure, we have the same issue.
Thanks for this post , it was very useful.
I'm glad you like it. Thanks for your comment
I consider myself a pretty awesome JavaScript developer and often express that in my interaction with others but I honestly had never heard of Array.some().
It's a very handy method. It happens to everyone, we can't know everything :)
Good article, thank you!
Thanks you too for reading it.
Thanks, your post is awesome.
Lovely
Thanks for reading it.
Love this! I needed it :D
I'm glad it helps, and thanks again for reading it.
I absolutely love this post. Thank you ❤️
I'm glad you like it. Thanks for reading it
The only difference between some() and includes() is the parameter (the former is a function, the latter an element) or Did I miss something?
Yes, they are kinda similar. They both check if a given element exists in the array or not. They both return
true
orfalse
as output.includes()
takes the element to check and optionally the starting index.some()
takes a function as a parameter.Thanks for the information
Thanks for reading it
great! thank you.
Very useful article, thanks!
I'm glad it helps. Thanks for reading it
Thanks a lot, this is one most important post for me, I don't shame it.
Awesome, namesake. I was discussing with a Senior today about HOF and I just see this.
However I'm confused, what's the difference between filter() and find()
I enjoyed every bit of this, simple clear examples. Now depends on how we implement them
Hi Ibrahim, thanks for the article. One thing to note is that the implementation for sort is correct but the comments are wrong.
Thanks for reading it. Now it's correct