JavaScript Array ForEach Loop Trick

In JavaScrupt. arrays have one interesting and usiful built-in method, which is the forEach() method.

What does the ForEach() Method do?

The forEach() method runs through all elements in an array. This greatly reducesed the amount of code if it does not exist. For example, I want to console.log() out all elements. Without the forEach() loop, the code would look like this:
var arr = [1,2,3,4]
    for(let i = 0;i<arr.length;i++){
    	console.log(arr[i]);
    };
And with the forEach() loop, the code looks like this:
var arr = [1,2,3,4]
    arr.forEach(item=>{
    	console.log(item);
    });
I like the second way.

Reverse the order of an array

In this article, I have made a function to generate an array with the reversed order from the original. Essentially, this is done by using the forEach() loop.

Looking for more than one array element

If we are looking for one element or its index, we can just use the array.find() or array.findIndex() method to get it done. But what if we want to find multiple.

The array.forEach() method comes in handy.
var arr = [1,2,3,4,2,3,4,2]
    arr.forEach((item,i)=>{
    	if(item == 2)console.log(i);
    });
//looking for the index of 2 in the array.
//1,4,7

Get the elements out.

var newArr = [];
var arr = [1,2,3,4,2,3,4,2]
    arr.forEach((item,i)=>{
    	if(item == 2)newArr.push(item);
    });
//get all 2 out into the new array.

Return will not stop the forEach Loop

var newArr = [];
var arr = [1,2,3,4,2,3,4,2]
    arr.forEach((item,i)=>{
    	if(item == 2)return false;
	console.log(item);
    });
//1,3,4,3,4

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser