If you’re new to JavaScript arrays, you’d be surprised how many useful built-in functions they have.
Today, I’ll show you 4 of them.
You can also get a deeper dive into a specific topic by reading dedicated articles:
-
How to iterate over an array with
forEach
-
How to transform a JS array with
map
- How to use Array.filter to remove unwanted elements from the array
-
How to reduce a JS array to a single value with
reduce
Array.filter
The filter
function is useful when you’d like to quickly remove some elements from the array.
const arr = [ -1, 2, 4, 0, -5, 7 ];
const positives = arr.filter(item => item > 0);
console.log(positives); // [ 2, 4, 7 ]
Note that the array arr
doesn’t change as filter
always returns a new array and never modifies the initial one.
Array.forEach
The built-in forEach
method is very commonly used by the Junior JS devs.
You can use it to iterate over an array, pretty much like the regular for loop:
const arr = [ -1, 2, 4, 0, -5, 7 ];
arr.forEach((item) => {
console.log(item); // print the array element to the console
});
Array.map
Similarly to forEach
, you can use map
to iterate over an array in JavaScript. The difference is that you can
transform an array into the new one while iterating over it.
Here I’m doubling every value in the array and thus getting a new one.
const arr = [ -1, 2, 4, 0, -5, 7 ];
const doubleArr = arr.map(item => item * 2);
console.log(arr); // [ -1, 2, 4, 0, -5, 7 ]
console.log(doubleArr); // [ -2, 4, 8, 0, -10, 14 ]
You can see two separate console.log
statements to demonstrate that similarly to filter
,
the initial array doesn’t change with map
.
Array.reduce
The function reduce
is one of the most complicated array functions for beginners, but once you learn how to use
it becomes very handy.
Here’s how you can use Array.reduce
to calculate the sum of the array elements:
const arr = [ -1, 2, 4, 0, -5, 7 ];
const sum = arr.reduce((prev, cur) => prev + cur, 0);
console.log(sum); // 7