Tags

Front End

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

  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"


*/

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

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

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

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

Alt Text


Guest Blogger

botanical profile

Special thanks to our guest blogger Kauress a Coding instructor for Cultivating Coders, game dev, dogs & VR, for her contribution to the Ronald James Blog this week.

Visit the original link for this blog here.

twitter dev github 

Who Are Ronald James?

We are a leading niche digital & tech recruitment specialist for the North East of England. We Specialise in the acquisition of high-performing technology talent across a variety of IT sectors including Digital & Technology Software Development.

Our ultimate goal is to make a positive impact on every client and candidate we serve - from the initial call and introduction, right up to the final delivery, we want our clients and candidates to feel they have had a beneficial and productive experience.

Contact our Team

If you’re looking to start your journey in sourcing talent or find your dream job, you’ll need a passionate, motivated team of experts to guide you. Check out our Jobs page for open vacancies. If interested, contact us or call 0191 620 0123 for a quick chat with our team.

Let's be Friends!

Follow us on our blog, FacebookLinkedInTwitter or Instagram to follow industry news, events, success stories and new blogs releases.

 

Back to Blog

</Follow Us>