Useful JavaScript array methods - Part 2
Published: 2020-07-10 17:59:25

JavaScript provides a bunch of helpful methods for working with arrays. This article, which is a follow up to [my previous post](https://dev.to/phyllis_yym/useful-javascript-array-methods-294l), will take you through some of the commonly used array callback methods. Again, I will group these methods by the _purpose_ of data transformation. 

We will use ES6 arrow functions in the examples below. If you haven't used them and would like to find out more about it, you may find [this article](https://dev.to/sarah_chima/arrow-functions-in-es6-24) helpful. 

## Table of content
1. Iterate - forEach
2. Transform - map
3. Filter - filter
4. Query - every, some

## Iterate - forEach
![iterate](https://media0.giphy.com/media/q1mHcB8wOCWf6/giphy.gif?cid=ecf05e47a672de1552fb393e3a77ddfb602ca5a3a7feeb36&rid=giphy.gif "Homer goes over each page of a book")

This method is used for running a function for each array element. You can also get the current index of each element if you need it. 

### Examples 1 & 2: extract values from an array of objects

```javascript
const restaurants =[{
  name: 'Tasca da Avenida',
  cuisine:'Mediterranean',
  rating: 4.3
 },
 {
  name:'Decor & Salteado',
  cuisine:'European',
  rating: 4.6
 },
 {
  name:'Carnes do Convento',
  cuisine:'Mediterranean',
  rating: 4.8
 }
]

//printing all restaurants' names
restaurants.forEach((r) => {
  console.log(r.name);
});

// Tasca da Avenida
// Decor & Salteado 
// Carnes do Convento

//printing all restaurants' name with their indices
restaurants.forEach((r, index) => {
  console.log(`${index}: ${r.name}`);
});

// 0: Tasca da Avenida
// 1: Decor & Salteado
// 2: Carnes do Convento

```
### Example 3: multiply each element in the array by 3

```javascript
const numbers = [2,4,6,8,10];
numbers.forEach((num) => {
  console.log(num * 3);
});

numbers
// 6
// 12 
// 18
// 24
// 30

```

## Transform - map
![transform](https://media3.giphy.com/media/5WJlk4CjBWZ5SNE4SC/giphy.gif "a car transforms into a robot")

This method iterates over each element of an array and transforms them into new elements. The original array will not be changed, but a new array, consists of these new elements, will be created.

## When to use map and forEach?
map: it returns values after manipulating data of the original array and those values are saved in a new array which can be used later.

forEach: There is no return value from the method. It only manipulates the data of the original array without creating a new array. 

Therefore if we simply want to do something with the array without creating a new array, we can use .forEach(). But if we want to capture the result of data manipulation in a new array, we should go for .map(). 

### Example 1: Transform each element in an array and save them in a new array

```javascript
const tea = ['cranberry', 'breakfast', 'earl grey', 'strawberry'];

// turn the tea names into uppercase characters and save them in a new variable uppercased
const uppercased = tea.map((t) => {
  return t.toUpperCase();
});

console.log(uppercased);

//["CRANBERRY", "BREAKFAST", "EARL GREY", "STRAWBERRY"]

```
### Example 2: return an object which includes the numbers in the array and whether each of them can be divided by 5 

```javascript
const numbers = [ 5, 3, 7, 10, 15];

const fiveMultiples = numbers.map((num) => {
  return {
    value: num,
    dividedByFive: num % 5 === 0
  }
});

fiveMultiples
//0: {value: 5, dividedByFive: true}
//1: {value: 3, dividedByFive: false}
//2: {value: 7, dividedByFive: false}
//3: {value: 10, dividedByFive: true}
//4: {value: 15, dividedByFive: true}

```
## Filter -filter
![filter](https://media1.tenor.com/images/ac630f336ff980d57815b41e72f53e88/tenor.gif?itemid=16846839 "making filter coffee")

.filter() returns a new array with elements which fulfils a condition specified by you. It works like this:

1. It loops over each element of an existing array.
2. If the element _fulfils_ a testing function specified by you, the result will be _true_ and that element will be _included_ in the new array.
3. If the element _does not pass the testing function_, the result will be _false_ and that element will be _excluded_ from the new array.
4. The original array will not be changed.

### Example 1: find out numbers which are greater than 100 and save them in a new array bigNumbers.

```javascript
const numbers = [10, 50, 102, 789, 5, 101];
const bigNumbers = numbers.filter(num => num > 100);
bigNumbers
// [102, 789, 101]
```

### Example 2: find out Mediterranean restaurants and save them in a new array called seacrhResult.

```javascript
const restaurants = [{
    name: 'Tasca da Avenida',
    cuisine: ['Mediterranean', 'Seafood'],
    rating: 4.3
  },
  {
    name: 'Decor & Salteado',
    cuisine: ['European', 'International'],
    rating: 4.6
  },
  {
    name: 'Carnes do Convento',
    cuisine: ['Mediterranean', 'Steakhouse'],
    rating: 4.8
  }
]

const searchResult = restaurants.filter((r) => {
  return r.cuisine.includes("Mediterranean");
})

searchResult

//{name: "Tasca da Avenida", cuisine: Array(2), rating: 4.3}
//{name: "Carnes do Convento", cuisine: Array(2), rating: 4.8}

```

## Query - every, some
![query](https://media0.giphy.com/media/KzyMcEfDh4Jiw/giphy.gif?cid=ecf05e475f11d2437637340d7d960631e2c63e2d87f4fbeb&rid=giphy.gif "It's funny because it's true")

## Every 
.every() is used when we want to see if all the elements in an array passes a condition defined by us. It returns a boolean value. In other words, if all the elements passes the condition, it will return true. Otherwise, it will return false.

### Example: check if all the restaurants above have a rating of at least 4.5.

```javascript
const allGoodRestaurants = restaurants.every(restaurant => restaurant.rating >= 4.5);

allGoodRestaurants
//false
```

## Some
.some() is similar to .every(). The only difference is, instead of checking if all array elements fulfil the condition, .some() only checks if at least one array element passes the test function.

In other words, if one or more elements passes the test function, it will return true. If none of the elements fulfils the condition, it will return false. 

### Example: check if at least one of the restaurants above has a rating of at least 4.5.

```javascript
const someGoodRestaurants = restaurants.some(restaurant => restaurant.rating >= 4.5);

someGoodRestaurants
//true
```
Thanks for reading! This article is far from comprehensive. There are still some methods which have not been covered. If you want to find out more about JS array methods, you can check out the docs on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). It's really good reference for learning and understanding how they work. 

<a href="https://www.buymeacoffee.com/phyllisyymo" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>