Ditch For... Loops - How to Use ES6 Array Methods to Loop Over An Array
Tags: webdev, programming, javascript, tutorial
Published: 2021-05-04 21:06:21

Do you remember something like this?

``` javascript
var text;

for (i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}
```

For those of you completely new to using JavaScript, let’s break down that code spippet fellas.

- All that statement is saying is that – “i is initially equals to zero. For as long as i is less than five, run the code inside the code block (i.e update the ‘text’ variable) and increment i by one (signified with the ++).

This used to be the standard way of looping through an array of items. 

**Used to.**

**EmcaScript 2016 (ES6)** came with a set of utility methods for looping through an array. For those of you wondering, EmcaScript is a general-purpose programming language, standardised by Ecma International according to the document ECMA-262.

**I like to think of EmcaScript as a new, modern and improved way of writing JavaScript.**


> 
N/B: If you’re looking for a more in-depth guide on ES6 syntax, I’ll recommend  [HTML To React By Sleepless Yogi](https://gumroad.com/a/834147443) . It’s really good!

These array iterators includes:
- Array.map()
- Array.find()
- Array.filter()
- Array.forEach()
- Array.every()
- Array.some()
- Array.sort()
- Array.reduce()

To properly understand how these methods work, we have to first understand two concepts:

- The size of an array
- The shape of an array

Consider this code:

``` javascript
const team = [
{
name: 'jack',
position: 'backend engineer'
},
{
name: 'lara',
position: 'ux designer'
},
{
name: 'kingsley',
position: 'developer'
},
{
name: 'mark',
position: 'manager'
},
{
name: 'chris',
position: 'developer'
}
]
```javascript

There are two thing to note about this array:

- It has a size of five items (objects),
- Each item has a shape: a name and position.

With these in mind, all of the array iterator methods has it’s own behaviour:

- ### map()

  - Behaviour: Changes the shape, but not the size,
  - Example: Get just the name of everyone on the team.

```javascript
team.map((member) => {
return member.name; 
})
//Result: ['jack', 'lara', 'kingsley', 'mark', 'chris']
```
### sort()
  - Behaviour: Changes neither the size nor the shape, but changes the order.
  - Example: Get the team members in alphabetical order.

```javascript
team.sort();
//Result: [{name: 'chris', position: 'developer'}, {name: 'jack' ...}]
```

### filter()

- Behaviour: Changes the size, but not the shape.
- Example: Get only the developers.

```javascript
team.filter((member) => {
return member.position = “developer”; 
})

// Result: [{name: 'kingsley', position: 'developer'}, {name: 'chris', position:'developer'}]
```
### find()
  - Behavior: Changes the size to exactly one, but not the shape. It Does not return an array. 
  - Example: Get the manager.

```javascript
team.find((member) => {
return member.position = manager; 
})

// Result: {name: 'justin', position: 'manager'}
```

> 
N/B: If there were two managers present, find() will only return the first

### forEach()
  - Behaviour: Uses the shape, but returns nothing.
  - Example: Give all members a bonus!

```javascript
Function sendBonus(member) {
	//code for bonus goes here\
}

team.forEach((member) => {
sendBonus(member); 
})

//Result: Jack gets a bonus! Lara get a bonus!… (but no return value).
```

### reduce()
  - Action: Changes the size and the shape to pretty much anything
you want.
  - Example: Get the unique team positions.

```javascript
const uniquePos = team.reduce((uniquePos, member) => {
 if (uniquePos.includes(member.position)) {
 return uniquePos;
 }
 return [...uniquePos, member.position];
 }, []);
// Result: [‘backend engineer’, ‘ux designer’, ‘developer’, ‘manager’]
```

A bit confused, let’s break down this code guys.

- The essence of this all is to get every unique postion of each member. Duplicate positions (developer) will be picked once.

- The first parameter taken by the reduce method is the ‘collectedValue’from the last iteration. When the iteration is just starting, then the reduce() second argument ([] in our case) will be used. For every iteration, the collected or total value is added the current item.

- In our case, when iteration just starts, the initial value [] wraps the current item in the array. 

-  The conditional checks to see if the total value (the array at this point in the loop) includes the position of the current member. If it does, the position is ignored and the CollectedValue is returned as it was. If not, the position of the current member is added to the array (with the spread operator).

### every()
  - Behavior: Changes neither the size nor the shape. Returns a Boolean: true if all items meet a condition, false if any doesn’t.
  - Example: Check if all items are objects.

```javascript
team.every((member) => {
return typeof member = object;
})

// Results: True
```
### some()
  - Behavior: Changes neither the size nor the shape. Returns a Boolean: true if any of the items meet a condition, false if all doesn’t.
  - Example: Check if any of the items is number.

```javascript
team.some((member) => {
return typeof member = number;
})

// Result: False
```

That’s it. I hope you learnt something from these brothers and sisters. If you did, consider buying me my favourite fruit:

<a href="https://www.buymeacoffee.com/ubahthebuilder"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a pineapple&emoji=🍍&slug=ubahthebuilder&button_colour=e0b51a&font_colour=000000&font_family=Cookie&outline_colour=000000&coffee_colour=FFDD00"></a>

I will really appreciate it.

Thank you and see you soon.