Array functions in JavaScript
Tags: javascript, codenewbie, tutorial, functional
Published: 2020-02-27 09:13:00

## 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). And in this article, I will be documenting some of my favorite ones. 
 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vrra665lnb0y13xzlkxo.jpg)

## 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
```javascript
arr.filter((element, index, originalArray) =>  Boolean);
```

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
```javascript
const numbers = [1, 2, 3, 4, 5, 6, 7];
const evenNumbers = numbers.filter(element => element % 2 === 0);
console.log(evenNumbers); // [ 2, 4, 6 ]
```

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.
```javascript
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 ]
```

## .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
```javascript
arr.map((element, index, originalArray) =>  NEW_VALUE);
```

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.
```javascript
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 ]
```

## .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
```javascript
arr.reduce((currentValue, element, index, originalArray) =>  NEW_VALUE, 
DEFAULT_VALUE);
```

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
```javascript
const numbers = [1, 4, 2, 5, 6, 3, 5, 5];
const sum = numbers.reduce((currentSum, element) => currentSum + element, 0);
console.log(sum); // 31
```

Example 2: get frequency of names
This example takes number of names and returns object saying how many times which occurred.
```javascript
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 }
```

## .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
```javascript
arr.forEach((element, index, originalArray) =>  { });
```
As said before, function has same signature as filter and map. Just doesn’t return any value.

Example 1: print all element
```javascript
const names = ["John", "Joe"];
names.forEach(name => {
    console.log(name);
});
// John
// Joe
```
## 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](https://github.com/kristijan-pajtasev/javascript-array-functions-demo).