# Array Methods - Most Useful Ones with Examples

As a JavaScript developer, it's important that you are familiar with array methods and how to handle the data in an array format. In this article, I will summarise some of the most commonly used array methods along with examples to understand them better. 


## Array.forEach() Method
The `forEach()` method loops through an array and execute a provided function once for each array element.

```javascript
// Inline callback function
array.forEach(function(currentValue, index, arr) { 
      // Do what you like to do
}, thisValue);

// Arrow function
array.forEach((currentValue, index, arr) => { 
      // Do what you like to do
}, thisValue);
```

The syntax above covers two main ways of writing the `forEach()` method. 

The callback function is specified in the `forEach()` method and executes only once for each element. It can accept the specified arguments to be used within the callback function. 

Some of the parameters passed would be optional depending on what you like to do.

- `currentValue` is the current element from the array that is being processed. This is the only parameter that is required. 

- `index` is the index of `currentValue`. This is optional.

- `arr` is the array that was passed to the `forEach()` method.

- `thisValue` is the value that will be used in the callback function. This is optional.


Let's look into some examples to see how the `forEach()` method works with real data.


```javascript
const dogs = ["Pug", "Shiba inu", "Rottweiler", "Golden retriever", "German shepherd"];
const pluralS = "s";

dogs.forEach((currentDog, index) => {
  if(index > 1) {
    console.log(`I have ${index} ${currentDog}${pluralS}.`);
  } else {
    console.log(`I have ${index} ${currentDog}.`);
  }
});

// Output
I have 0 Pug.
I have 1 Shiba inu.
I have 2 Rottweilers.
I have 3 Golden retrievers.
I have 4 German shepherds.

```

The `forEach()` method is useful when you want to loop through an array of any type of item. You could achieve the same results with `for loop`, however the `forEach()` method provides you with cleaner codes. 

The `forEach()` method is also handy when you want to iterate an array but you don't want to return anything. If you want to return value, consider using the `map()` method that we are going to look into next.


## Array.map() Method
The `map()` method is one of the most used and popular methods on my list in the article. It executes a provided function once for every element in the array and it returns a new array that is created. 

The syntax of the `map()` methods are as follows:

```javascript
// Inline callback function
array.map(function(currentValue, index, arr) { 
      // Do what you like to do
}, thisValue);

// Arrow function
array.map((currentValue, index, arr) => { 
      // Do what you like to do
}, thisValue);
```

The parameters options are the same as the `forEach()` method -  `currentValue` is required and others are optional. Now, let's look at some of the examples.

```javascript
// Example 1
const dogsArray = ["Pug", "Shiba inu", "Rottweiler", "Golden retriever", "German shepherd"];

const newDogsArray = dogsArray.map(dog => dog.concat("s"));
console.log(newDogsArray);

// Output
['Pugs', 'Shiba inus', 'Rottweilers', 'Golden retrievers', 'German shepherds']

// Example 2
const dogsDetails = [
    {type: "pug", age: 2, color: "light brown"}, 
    {type: "shiba inu", age: 1.2, color: "brown"},
    {type: "rottweiler", age: 0.5, color: "brown and white"},
    {type: "golden retriever", age: 3, color: "black"},
    {type: "german shepherd", age: 1.3, color: "black"},
];

const newDogsDetails = dogsDetails.map(dog => {
    return `My ${dog.type} is ${dog.age} years old.`;
});
console.log(newDogsDetails);

// Output
['My pug is 2 years old.', 'My shiba inu is 1.2 years old.', 
  'My rottweiler is 0.5 years old.', 'My golden retriever is 3 years old.', 
  'My german shepherd is 1.3 years old.']
```

The `map()` method is useful because you can create a new array without affecting the original array. However, don't forget to return the value except when you write an arrow function with one line of statement code. 


## Array.reduce() Method
The `reduce()` method executes a reducer function (that you provide) on each element of the array, and it returns a single output value. 

```javascript
// Inline callback function
array.reduce(function(previousValue, currentValue, currentIndex, arr) {
      // Do what you like to do
}, initialValue)

// Arrow function
array.reduce((previousValue, currentValue, currentIndex, arr) => {
      // Do what you like to do
}, initialValue);
```
Let's look into the parameters in detail. 

- `previousValue` is the result from the previous call to the callback function. For the first round, it will be `array[0]` unless `initialValue` is specified.

- `currentValue` is the current element from the array that is being processed. For the first round, it will be `array[1]` if there is no `initialValue` specified and it will be `array[0]` if the the`initialValue` is specified.

- `currentIndex` is the index of `currentValue`. On the first call, it is `0` if initialValue was specified, otherwise it is`1`.

- `arr` is the array that was passed to the `reduce()` method.

- `initialValue` is the starting value to the accumulation and `previousValue` when the callback is called for the first time.

When you read the explanation and each meaning, it can be confusing. The simplest way to understand the `reduce()` method is to return the sum of all the elements in an array. Let's look at some examples now.

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

const sum = numsArray.reduce((accumulator, number) => {
  console.log("accumulator: " + accumulator); // To see what is happening
  return accumulator + number; 
}, 0);
console.log(sum);

// Output
accumulator: 0 // This is because we set `initialValue` to be `0`
accumulator: 1
accumulator: 3
accumulator: 6
accumulator: 10
15 // sum of all the elements in an array
```
Now we understand what's happening behind the scenes, let's look into another example.

```javascript
const numsArray = [1, 2, 4, 551, 39, 38, 20, 5, 10, 2, 1, 1, 1, 20, 20];

const sortedNumsObj = numsArray.reduce((acc, current) => { 
    acc[current] ? acc[current]++ : acc[current] = 1    
  return acc;
}, {});
console.log(sortedNumsObj);

// Output
{1: 4, 2: 2, 4: 1, 5: 1, 10: 1, 20: 3, 38: 1, 39: 1, 551: 1}
```
The above example demonstrates how to count the same elements in the array. It returns in an object format with the element as keys and the number of elements as values because we set the initial value to be an empty object. It's very useful to sort the data and know how many of each exist but don't forget to return the result, which is the accumulator in this case. 



## Array.sort() Method
The `sort()` method is useful to sort out the array of data. The default sort order is ascending but you can control the order once you understand how it works. 

```javascript
// Inline compare function
array.sort(function(a, b) { 
      // Do what you like to do
})

// Arrow function
array.sort((a, b) => {
      // Do what you like to do
} )
```

Simply pass 2 parameters that you want to compare: 
- `a` is the first element for comparison.
- `b` is the second element for comparison. 

Let's start looking at some examples with numbers array and then move on to see how alphabetical order can be handled. 

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

const ascending = numsArray.sort();
console.log(ascending);

const descending = numsArray.sort((a, b) => b - a);
console.log(descending);


// Output
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
```

```javascript
const dogs = ["Pug", "Shiba inu", "Rottweiler", "Golden retriever", "German shepherd"];

// Alphabetical order
const sortedDogs = dogs.sort();
console.log(sortedDogs);

// Output
['German shepherd', 'Golden retriever', 'Pug', 'Rottweiler', 'Shiba inu']

const dogsDetails = [
    {type: "pug", age: 2, color: "light brown"}, 
    {type: "shiba inu", age: 1.2, color: "brown"},
    {type: "rottweiler", age: 0.5, color: "brown and white"},
    {type: "golden retriever", age: 3, color: "black"},
    {type: "german shepherd", age: 1.3, color: "black"},
];

const sortedDogsDetails = dogsDetails.sort((a, b) => {
    return a.type < b.type ? -1 : 1;
});

// Output
[{type: 'german shepherd', age: 1.3, color: 'black'}
  {type: 'golden retriever', age: 3, color: 'black'}
  {type: 'pug', age: 2, color: 'light brown'}
  {type: 'rottweiler', age: 0.5, color: 'brown and white'}
  {type: 'shiba inu', age: 1.2, color: 'brown'}]

```
The comparator always returns either `-1`, `0`, or `1`. If the two values' comparison evaluates something negative, the first element is placed before the second one in an array. If it evaluates positive, the first element comes after the second one. If it returns 0, then the two elements are equal. 

As explained, it is handy to sort your data array but be mindful that the `sort()` method overwrites the original array.
 

## Array.filter() Method
The `filter()` method returns a new array that meets the given condition. The syntax is shown as follows:

```javascript
// Inline callback function
array.filter(function(currentValue, index, arr) { 
      // Do what you like to do
}, thisValue);

// Arrow function
array.filter((currentValue, index, arr) => { 
      // Do what you like to do
}, thisValue);
```

The `filter()` method always returns an array, which means if you don't pass any parameters it will return an empty array. Now let's check some examples. 

```javascript
const dogsDetails = [
    {type: "pug", age: 2, color: "light brown"}, 
    {type: "shiba inu", age: 1.2, color: "brown"},
    {type: "rottweiler", age: 0.5, color: "brown and white"},
    {type: "golden retriever", age: 3, color: "black"},
    {type: "german shepherd", age: 1.3, color: "black"},
];

const filteredArray = dogsDetails.filter(dog => dog.age > 1.2);
console.log(filteredArray);

// Outcome
[{type: "pug", age: 2, color: "light brown"}, 
  {type: "golden retriever", age: 3, color: "black"},
  {type: "german shepherd", age: 1.3, color: "black"}];
```

The `filter()` comes in convenient if you want to filter your data with the condition. To expand the scenario, let's consider the following cases and the better functions that you may want to use instead of the `filter()`.

### `every()`: Only if you want to know true/false if the condition meets with all of the elements in an arrray

```javascript
const filteredArray2 = dogsDetails.every(dog => dog.age > 0.5);
console.log(filteredArray2);

// Outcome 
false 
``` 

### `some()`: Only if you want to know true/false if the condition meets with some of the elements in an array

```javascript
const filteredArray3 = dogsDetails.some(dog => dog.age > 0.5);
console.log(filteredArray3);

// Outcome 
true 
``` 

### `find()`: Only if you want to return the first element that meets the condition

```javascript
const filteredArray4 = dogsDetails.find(dog => dog.color === 'black');
console.log(filteredArray4);

// Outcome 
{type: "golden retriever", age: 3, color: "black"}
``` 

## Summary
We have looked into some of the most popular and used array methods. It's important that you know what is the best approach to handle your data and consider which one is the most efficient way to handle the array. 
 









  
