forEach( ), sort( ) & filter( ) for newbies
Tags: javascript, webdev
Published: 2020-01-10 05:17:39


## forEach()

 ES6 has introduced the forEach() method which allows you to loop through an array. Arrays as you may already know are of the type 'object'. In contrast to the string,number,boolean, undefined and symbol types which are primitive data types. For example if we console.log the *typeof* operator to find the *typeof* array, *object*will be logged, as seen below:

```
const yummies = ['Ice-cream','Cupcake','Donut','Cupcake'];
console.log(typeof yummies)// will log "object"
```
Well, what does this mean in context of the forEach method which we're talking about. To back track a bit more, methods are functions that are specific to an object. So we can apply an array method called 'slice()' which will take 2 parameters: 

  1. The starting index in the array to begin the slice method
  2. The last index in the array *before* which you want to end your slice at

The slice method when applied on the 'yummies' array will return a new array with the *sliced* elements. For example:

```
const slicedYummies = yummies.slice(0,3);
console.log(slicedYummies);
*/
will console.log["Ice-cream", "Cupcake", "Donut"]
As the slice() method  starts at index 0 and ends just before index 3. Which is index 2,. Therefore, the 2nd Cupcake which is at index 3 isn't present
*/

```
Similarly we can apply the forEach() method on any array in JavaScript. This method also takes parameters. First gloss over the syntax.

### Syntax:

arr.forEach(function fxnName(currentItem,index,arr),thisArg){
//some code here
});

The forEach() method takes the following parameters:

### 1st Parameter of the forEach() method:

 The first parameter is a function that will be executed *on/for each* element in the array. This is called a  *callback function*  and it in turn can take 3 arguments:

1. Current Item: The current item in the array. **Required parameter**. For example "Ice-cream" will be the starting/current item in the array.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/e1glj0cn6tqzd4ifnlw4.png)

2. Index: The index of the current item in the array. **Optional parameter**. For example index 0.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/qn3r3z655a88ag0d1rvi.png)

3. Array: The array on which forEach() will enact. **Optional parameter**. For example in this case["Ice-cream", "Cupcake", "Donut", "Cupcake"].

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/l6ufswx0q10sr54oi2i5.png)

### 2nd  Parameter of the forEach() method:

 The 2nd parameter that the forEach method can take is:

1.thisArg:  The value to use as *this* while executing callback. *Optional parameter*. This is covered later in another article.



Let's have a look at the forEach() method on the *yummies* array:

```
yummies.forEach(function logYummies(item,index, yummies){
  console.log(item + ' The index is ' + index +' The whole array is: ' + arr);
});

/*
Console.logs the following:

"Ice-cream The index is 0 The whole array is: Ice-cream,Cupcake,Donut,Cupcake"

"Cupcake The index is 1 The whole array is: Ice-cream,Cupcake,Donut,Cupcake"

"Donut The index is 2 The whole array is: Ice-cream,Cupcake,Donut,Cupcake"

"Cupcake The index is 3 The whole array is: Ice-cream,Cupcake,Donut,Cupcake"


*/
```


In the above example, the forEach() method is applied on the yummies array via the '.' notation like so yummies.forEach(). And the forEach() method takes as an argument a function called *logYummies* which in turn takes 3 parameters: item, index and the whole array

Let's have a look at another simple example. There is an array with 5 elements of the number data type. You would like to multiply each element by 2 therefore, doubling the number.

With a for loop it will look like so:

```
let myMultiplier = [1,2,3,4,5];

for(let i =0; i < myMultiplier.length; i++){
  myMultiplier[i] = myMultiplier[i] * 2;
}
console.log(myMultiplier)// will log to [2, 4, 6, 8, 10]
```

And by using the forEach method, it will look like this:

```

myMultiplier.forEach(function multiply(item, index, myMultiplier){
myMultiplier[index] = item * 2
})

console.log(myMultiplier)// will log to [2, 4, 6, 8, 10]
```



## filter()

The ES6 filter() method also acts upon arrays in JavaScript. It will filter an array based on some filter criteria and return a **new array**
with the filtered elements.

### Syntax

Similiar to the forEach() method:

 array.filter(function fxnName(currentItem, index, array), thisArg){
//some code
});


### 1st Parameter of the filter() method:

 
The first parameter is a function that will be executed on  elements in the array. This is called a callback function and it in turn can take 3 arguments:

1. Current Item: The current item in the array. Required parameter. For example "Ice-cream" will be the starting/current item in the array.

2. Index: The index of the current item in the array. Optional parameter. For example index 0.

3. Array: The array on which filter() will enact. **Optional parameter**. For example in this case["Ice-cream", "Cupcake", "Donut", "Cupcake"].

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/cqiyk1imau1anvxni99o.png)

### 2nd  Parameter of the filter() method:

 The 2nd parameter that the filter method can take is:

1.thisArg:  The value to use as *this* while executing callback. *Optional parameter*. This is covered later in another article.

Let's filter the yummies array and remove the duplicate cupcakes

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/hbrsaokql039j6tvi184.png)

```
const yummies = ['Ice-cream','Cupcake','Donut','Cupcake'];
const  filteredYummies = yummies.filter(function filterYums(currentItem,index,yummies) {
  if (yummies.indexOf(currentItem) === index) {
    return currentItem;
  }
})
console.log(filteredYummies);//will log ["Ice-cream", "Cupcake", "Donut"];

/*
The indexOf() method returns the **index/POSITION** of the first occurrence of a specified string value (example 0,1,2 etc)
The filter() method 'filters' through each index and applies 
the indexOf method on an array item at a particular index
We check if the index of the currentItem in the yummies array is it's first occurrence 
if so then it is part of the filteredYummies array
So during the 4th iteraton , index or  *i* is 3 and the *first* occurrence of *Cupcakes* using yummies.indexOf("Cupcake) was 1.
Therefore 3 === 1 is false
All in All:  the indexOf/position of the item in the array should be equal to *i*
*/

```

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/vb1xbgzt94rtanipeh5b.png)


## sort()

The sort() method as the name implies will sort elements in an array. By default elements in an array will be sorted in ascending or alphabetical order. 

### Syntax

nameOfArray.sort();

## Example:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/j2jqbgmnmb8r448mqhsh.png)


```
const yummies = ['Ice-cream','Cupcake','Donut','Cupcake'];
yummies.sort();
console.log(yummies)

/* 
console.log will output the following in alphabetical order:
["Cupcake", "Cupcake", "Donut", "Ice-cream"]
*/
```
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/741zbu1z00nazecxe7qd.png)

You can also sort according to an alternative order for example in descending order. In such a case you will pass a *comparer* function to the sort() method. And the syntax will now be:

   nameOfArray.sort(compareFunction);

Let's have a look at another example and sort the yummies array items in descending alphabetical order that is from Z-A.

## Example 2

```
const yummies = ['Ice-cream','Cupcake','Donut','Cupcake'];
function descendingOrder(a,b){
  return b > a;
}
yummies.sort(descendingOrder);
console.log(yummies)// will output ["Ice-cream", "Donut", "Cupcake", "Cupcake"]

```
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/kechv29jnn1litir2vgb.png)