DEV Community

Cover image for  forEach( ), sort( ) & filter( ) for newbies
Kauress
Kauress

Posted on • Edited on

forEach( ), sort( ) & filter( ) for newbies

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"


Enter fullscreen mode Exit fullscreen mode

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
*/



Enter fullscreen mode Exit fullscreen mode

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

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

Alt Text

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

Alt Text

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"


*/


Enter fullscreen mode Exit fullscreen mode

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]


Enter fullscreen mode Exit fullscreen mode

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]


Enter fullscreen mode Exit fullscreen mode

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

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



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*
*/



Enter fullscreen mode Exit fullscreen mode

Alt Text

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



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"]
*/


Enter fullscreen mode Exit fullscreen mode

Alt Text

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"]



Enter fullscreen mode Exit fullscreen mode

Alt Text

Top comments (2)

Collapse
 
romangraef profile image
Roman Gräf

Hey, just wanted to ask: Shouldn't the callback of .filter() return a truthy/falsey value? I guess it works in this case, but it could be confusing if someone tried to use filter in the sense of how .map() is supposed to be used. Also this probably fails if yummies contained a falsey value like an empty string which it wanted to keep.

Collapse
 
kauresss profile image
Kauress

Hi,the students for whom this was written only know some basic array methods and haven't done map() as yet. So I wrote this article around what they already know, as beginners getting into advanced JS. The filter() method iterates over each element in the array and passes it to the filterYums function. Yes, if the condition yummies.indexOf(currentItem) === index is met it will return true and that element will be passed to the new array. The condition does not check for falsey values like empty strings, null and undefined.