JS: Array Methods
Tags: javascript, arrays
Published: 2021-07-02 07:28:12

This post reviews the many available methods for handling Arrays in ES6 - with easy to understand examples that I hope will act as a reference whenever you need one of these methods.

>**Jump to:**
- [Find](#find-anchor)
- [Filter](#filter-anchor)
- [Map](#map-anchor)
- [Reduce](#reduce-anchor)

---

# Find() <a name="find-anchor"></a>

The find method, simply put, allows you to grab the first occurrence of an element from an array that matches the search criteria you provide it.

Bit of long sentence, but lets explain in a small example:

```javascript
const items = [
  { name: 'naruto', age: 20 },
  { name: 'sakura', age: 22 },
  { name: 'naruto', age: 40 }
]

const naruto = items.find((item) => {
// The search criteria
 return item.name === 'naruto'
});

console.log(naruto);
// { name: 'naruto', age: 20 }

```

Above, we have our items array, which is an array containing 3 elements, of which each is an object containing a name and age property. **[object, object, object]**


The example then creates a function called **‘naruto’** which is where we run the **find()** method.

The **find()** itself takes a function as a parameter, and this is used as the search criteria.

So what we’re saying is: 

Take my items array, run find on it, and search through each item until you find the **first occurrence** where **item.name** is equal to **‘naruto’**.


Hence when the function runs, we get a return of:

`{ name: ‘naruto’, age: 20 }`


Note that despite having 2 elements which have the name property equal to ‘naruto’, **find()** by it’s very nature only returns the **first occurrence**.

---

# Filter() <a name="filter-anchor"></a>

The filter method is pretty much exactly the same as the find() method as described above. The key difference being that instead of only returning the first occurrence that matches your provided search criteria, it returns a new array with all matching elements.

Take the below example:

```javascript
const filterItems = [
  { name: 'naruto', age: 20 },
  { name: 'sakura', age: 22 },
  { name: 'naruto', age: 40 }
]

const results = filterItems.filter((item, index) => {
 // The search criteria
 return item.name === 'naruto';
});

console.log(results);
// [ { name: 'naruto', age: 20 }, { name: 'naruto', age: 40 } ]
```

Just like, find(), we run through each element in the array and search given our criteria (which is the function we pass into the filter method as that's simply what filter() requires to work). We search for each match in the array, and then return a new array with all matching elements. Hence when we log results, we get: 

`[ { name: 'naruto', age: 20 }, { name: 'naruto', age: 40 } ]`


Why did you also pass **index** in the **filter()** functions arguments? 

This is just to demonstrate that filter, unlike find, can take an optional second parameter for the **index** number of the item in the array. This can be useful in many scenarios, though we do not make user of it in our above example.

---

# Map() <a name="map-anchor"></a>

Map is probably the most frequently used of the ES6 Array Methods, given its frequently used in React component creation to generate a collection of component elements from an array of data.


It's similar to filter() in that it takes in a function along with 2 parameters, item and index (these can be called whatever you like, but the order matters).

Unlike find and filter though, map() goes though each element in your array and maps custom return values to each array element, returning a customised element (per each element) into a new array.


Take the below example for a clearer picture:

```javascript
const employees = [
  { name: 'kakashi', id: 1 },
  { name: 'naruto', id: 2 },
  { name: 'sakura', id: 3 },
]

const elements = employees.map((item, index) => {
 // return each item back into a new array
 return `<div>${item.id} - ${item.name}</div>`;
});

console.log(elements);
// [
//   '<div>1 - kakashi</div>',
//   '<div>2 - naruto</div>',
//   '<div>3 - sakura</div>'
// ]
```

---

# Reduce <a name="reduce-anchor"></a>

Reduce, unlike the previous array methods, is an aggregator function.

This means it takes each element in an array, applies some provided logic to them and returns a single final value as the result.

Take the simplest of examples below:

```javascript
const numbers = [1,2,3,4,5];

sumOfNnumbers = numbers.reduce((total, currentNumber) => {
 total = total + currentNumber;
 return total;
});

console.log(sumOfNnumbers);
// 15
```

I find the clearest way to understand Reduce is breaking down the above example into steps:

>- We have an array of numbers.
- We run reduce on the array.
- reduce() takes in a function as it's argument.
- The function requires 2 arguments, usually something for the accumulative value to be stored (i.e. total), and another for the current element (i.e. currentNumber).
- We then set total = total + current number and return the result, given us a single sum of each value in our array - hence returning 15.