loading...
Cover image for Array functions in JavaScript

Array functions in JavaScript

chriss profile image Kristijan Pajtasev Updated on ・4 min read

Introduction

Over last few years JavaScript has come a long way. Probably starting with V8, we got NodeJS, language syntax improved a lot and it got in almost all parts of IT. It stopped being just toy web language. Today, we use it on backend, in analytics and even in satellites. But even before that, in version 5, we got some improvements that I personally love using. Array functions. And in this article, I will be documenting some of my favorite ones.

Alt Text

What are array functions?

Just like in other languages, JavaScript arrays have different properties and methods built in. In version 5, sometime in 2009, there was extension in this area. Many useful methods were added. Methods that enable us to write code in a functional way. This means we could skip for loops and creation of temporary variables. So, let’s start with first one. Filter.

.filter

Just like name implies, filter function filters out elements. Or if we want to say it a bit more technically, when running filter on an array, it will return new array with all elements satisfying our filter rule. This new array will be of same size or smaller than array we are running it on.

Function signature

arr.filter((element, index, originalArray) =>  Boolean);
Enter fullscreen mode Exit fullscreen mode

Filter function takes one parameter. Function that will validate if element satisfies our defined rule. This function will be executed on each element of array and receives three parameters, first being currently observed element, second one is index of that element and third one is original array. Return value of this function is boolean. If you want to keep element you return true, otherwise false.

Example 1: Get only even numbers from array

const numbers = [1, 2, 3, 4, 5, 6, 7];
const evenNumbers = numbers.filter(element => element % 2 === 0);
console.log(evenNumbers); // [ 2, 4, 6 ]
Enter fullscreen mode Exit fullscreen mode

Example 2: Filter out duplicates
One interesting, and very nice example of filter use is removing duplicated elements from array because this one uses all three of function parameters.

const arrayWithDuplicates = [1, 1, 2, 5, 3, 4, 4, 4,  5, 6, 7];
const arrayWithoutDuplicates = arrayWithDuplicates.filter(
    (element, index, originalArray) =>
        originalArray.indexOf(element) === index);
console.log(arrayWithoutDuplicates); // [ 1, 2, 5, 3, 4, 6, 7 ]
Enter fullscreen mode Exit fullscreen mode

.map

Map is function that takes array elements and converts them into different form. This can be extending element with some property, returning just one property value or something else. But always, returned array is of same length.

Function signature

arr.map((element, index, originalArray) =>  NEW_VALUE);
Enter fullscreen mode Exit fullscreen mode

We write map function same as filter, with difference in return. Returned value is one we will keep in new array.

Example 1: Return array of prices from array of objects
In this example we will have array of object containing property price, but we might want to get average price, minimum, maximum or anything else. For this it would be easier if we have just array of numbers. This is something we can use map for.

const priceObjects = [
    { price: 11.11 }, { price: 42.42 },
    { price: 99.99 }, { price: 29.99 }
];
const prices = priceObjects.map(element => element.price);
console.log(prices); // [ 11.11, 42.42, 99.99, 29.99 ]
Enter fullscreen mode Exit fullscreen mode

.reduce

Reduce method is a bit different and is used usually to reduce array into single value. That value can be a number, string, object or anything else. It is aggregate function. There are different use cases where reduce can be applied, but getting sum is kind of most often use case I have seen.

Function signature

arr.reduce((currentValue, element, index, originalArray) =>  NEW_VALUE, 
DEFAULT_VALUE);
Enter fullscreen mode Exit fullscreen mode

Function signature for reduce is a bit different than for filter and map. First difference is that reduce takes two arguments, first one is still function, but second one is default value. If we are doing sum of all numbers, default sum would be zero. This will be seen in example 1 bellow. Second difference is function given as first parameter. This function receives four parameters not three like map and filter. First parameter is current result of reduce. In first run that is default value, and in later iterations it changes. Last iteration return is final result of reduce. Rest of parameters are the same three parameters we receive in filter and map.

Example 1: Get sum of all numbers

const numbers = [1, 4, 2, 5, 6, 3, 5, 5];
const sum = numbers.reduce((currentSum, element) => currentSum + element, 0);
console.log(sum); // 31
Enter fullscreen mode Exit fullscreen mode

Example 2: get frequency of names
This example takes number of names and returns object saying how many times which occurred.

const names = ['John', 'Jane', 'Joe', 'John','Jenny', 'Joe', 'Joe'];
const namesFrequency = names.reduce((current, name) => {
    if(!current[name]) current[name] = 0;
    current[name]++;
    return current;
}, {});
console.log(namesFrequency); // { John: 2, Jane: 1, Joe: 3, Jenny: 1 }
Enter fullscreen mode Exit fullscreen mode

.forEach

This method is more like map and filter than reduce, but I decided to leave it for last because of one important reason. It does not return value. All functions before returned array or some reduced value. This one does not. So why would we want to use this function? If we just want to execute some work on array element, maybe just print out each element.

Function signature

arr.forEach((element, index, originalArray) =>  { });
Enter fullscreen mode Exit fullscreen mode

As said before, function has same signature as filter and map. Just doesn’t return any value.

Example 1: print all element

const names = ["John", "Joe"];
names.forEach(name => {
    console.log(name);
});
// John
// Joe
Enter fullscreen mode Exit fullscreen mode

Conclusion

These are just some of array functions, but ones I personally use most. While there are more advanced ways of using them, I do hope this post explained how. Because of them giving us more functional style of coding, there are many other benefits of using them like function chaining. But maybe more important, if underlying architecture would support it, it might be optimized for parallelism, which would give huge performance improvement.
All code examples used for this post can be found in my Github repository.

Discussion

pic
Editor guide
Collapse
aminnairi profile image
Amin

You should use the JavaScript syntax highlight for your article. It really makes the code stand out from your article that way.

console.log("no syntax highlight");
console.log("with syntax highlight");
Collapse
chriss profile image
Kristijan Pajtasev Author

Very good point, tnx. I updated it now