JavaScript

JavaScript Array Iteration Methods Example

Greetings readers, in this tutorial, we will explore the Array iteration methods in the javascript.

1. Introduction

JavaScript is an object-oriented programming language that allows the client-side scripting to interact with a user and deliver the dynamic pages. Most web browsers including Google Chrome, Mozilla Firefox, Safari, Internet Explorer, Microsoft Edge, Opera, etc. support it. The JavaScript scripting language includes:

  • Declaring variables
  • Maintaining the retrieving values
  • Defining and invoking functions
  • Defining classes
  • Load and use external modules
  • Define event handlers
  • And much more ….

1.1 Advantages of JavaScript Language

The pros of using the JavaScript scripting language are:

  • JavaScript is easy to learn
  • It executes on the client’s browser, so eliminates the server-side processing and be executed on any OS
  • JavaScript can be used with any type of web page e.g. PHP, ASP.NET, Perl etc
  • Web-page performance increases due to client-side execution
  • JavaScript code can be minified to decrease the loading time from the server
  • Many JavaScript-based application frameworks are available in the market to create Single page web applications e.g. AngularJS, ReactJS etc.

1.2 Disadvantages of JavaScript Language

The cons of using the JavaScript scripting language are:

  • Does not have any multi-threading or multi-processing capabilities
  • Does not allow the file reading and writing capabilities

1.3 Array Iteration methods in javascript language

Following table shows the different array methods in the javascript language.

MethodDescriptionExample
Array.forEach()This method calls a callback function once for each array element.myarray.forEach(myfunction);
Array.map()This method creates a new array by performing a function on each element of the array. It does not change the original array.myarray.forEach(myfunction);
Array.filter()This method creates a new array with elements that pass the test.myarray.filter(myfunction);
Array.reduce()This method runs a function on each element to produce a single value and it works from left-to-right in the array. Do note, this method does not reduce the original array.myarray.reduce(myfunction);
Array.reduceRight()This method runs a function on each element to produce a single value and it works from right-to-left in the array. Do note, this method does not reduce the original array.myarray.reduceRight(myfunction);
Array.every()This method checks if all the values of an array pass the test.myarray.every(myfunction);
Array.some()This method checks if some values of an array pass the test.myarray.some(myfunction);
Array.find()This method returns the value of the first array element that pass a test function.myarray.find(myfunction);
Array.findIndex()This method returns the index of the first array element that pass a test function.myarray.findIndex(myfunction);

2. JavaScript Array Iteration Methods Example

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7, and it works well.

2.2 Project Structure

Firstly, let us review the final project structure if you are confused about where you should create the corresponding files or folder later!

JavaScript Array Iteration Methods - Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will show how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

JavaScript Array Iteration Methods - Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.

JavaScript Array Iteration Methods - Project Details
Fig. 3: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

JavaScript Array Iteration Methods - Archetype Selection
Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

JavaScript Array Iteration Methods - Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javascript</groupId>
	<artifactId>Javascriptarraymethodstutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

3. Application Building

Let us see the sample code snippet to understand the array iteration methods in the javascript language.

index.jsp

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Index page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.2.1/css/bootstrap.min.css">
</head>

<body>
    <div class="container">
        <h2 align="center" class="text-muted">Array Iteration Methods in JavaScript</h2>
        <hr />

        <!-- JavaScript Array Iteration Methods Example -->
        <div id="title">
            <h5 class="font-weight-normal"><mark>Array Iteration Methods</mark> in javascript operate on every element of an array. The table below explains the different methods.</h5>
            <div> </div>

            <table class="table table-bordered">
                <thead>
                    <tr class="text-center">
                        <th scope="col">Method</th>
                        <th scope="col">Description</th>
                        <th scope="col">Example</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><code>Array.forEach()</code></td>
                        <td>This method calls a callback function once for each array element.</td>
                        <td><code>myarray.forEach(myfunction);</code></td>
                    </tr>
                    <tr>
                        <td><code>Array.map()</code></td>
                        <td>This method creates a new array by performing a function on each element of the array. It does not change the original array.</td>
                        <td><code>myarray.forEach(myfunction);</code></td>
                    </tr>
                    <tr>
                        <td><code>Array.filter()</code></td>
                        <td>This method creates a new array with elements that pass the test.</td>
                        <td><code>myarray.filter(myfunction);</code></td>
                    </tr>
                    <tr>
                        <td><code>Array.reduce()</code></td>
                        <td>This method runs a function on each element to produce a single value and it works from <em>left-to-right</em> in the array. Do <em>note</em>, this method does not reduce the original array.</td>
                        <td><code>myarray.reduce(myfunction);</code></td>
                    </tr>
                    <tr>
                        <td><code>Array.reduceRight()</code></td>
                        <td>This method runs a function on each element to produce a single value and it works from <em>right-to-left</em> in the array. Do <em>note</em>, this method does not reduce the original array.</td>
                        <td><code>myarray.reduceRight(myfunction);</code></td>
                    </tr>
                    <tr>
                        <td><code>Array.every()</code></td>
                        <td>This method checks if all the values of an array pass the test.</td>
                        <td><code>myarray.every(myfunction);</code></td>
                    </tr>
                    <tr>
                        <td><code>Array.some()</code></td>
                        <td>This method checks if some values of an array pass the test.</td>
                        <td><code>myarray.some(myfunction);</code></td>
                    </tr>
                    <tr>
                        <td><code>Array.find()</code></td>
                        <td>This method returns the value of the first array element that pass a test function.</td>
                        <td><code>myarray.find(myfunction);</code></td>
                    </tr>
                    <tr>
                        <td><code>Array.findIndex()</code></td>
                        <td>This method returns the index of the first array element that pass a test function.</td>
                        <td><code>myarray.findIndex(myfunction);</code></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <script type="text/javascript">
        // Array iteration methods.
        // forEach() method.
        [1, 2, 3].forEach(function(item, index) {
            console.log(item, index);
        });

        // map() method.
        const three = [1, 2, 3];
        const doubled = three.map(function(item) {
            return item * 2;
        });
        console.log("map()= " + doubled);

        // filter() method.
        const ints = [1, 2, 3];
        const evens = ints.filter(function(item) {
            return item % 2 === 0;
        });
        console.log("filter()= " + evens);

        // reduce() method.
        const sum = [1, 2, 3].reduce(function(result, item) {
            return result + item;
        }, 0);
        console.log("reduce()= " + sum)

        // some() method.
        const hasNegativeNumbers = [1, 2, 3, -1, 4].some(function(item) {
            return item < 0;
        });
        console.log("some()= " + hasNegativeNumbers);

        // every() method.
        const allPositiveNumbers = [1, 2, -3].every(function(item) {
            return item > 0;
        });
        console.log("every()= " + allPositiveNumbers);

        // find() method.
        const objects = [{
            id: 'a'
        }, {
            id: 'b'
        }, {
            id: 'c'
        }];
        const found = objects.find(function(item) {
            return item.id === 'b';
        });
        console.log(found);

        // findIndex() method.
        const objects2 = [{
            id: 'a'
        }, {
            id: 'b'
        }, {
            id: 'c'
        }];
        const foundIndex = objects2.findIndex(function(item) {
            return item.id === 'b';
        });
        console.log(foundIndex);
    </script>
</body>

</html>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

JavaScript Array Iteration Methods - Application on Tomcat
Fig. 6: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL to display the application’s index page and console output as shown in Fig. 7.

http://localhost:8082/Javascriptarraymethodstutorial/

Server name (localhost) and port (8082) may vary as per your Tomcat configuration.

JavaScript Array Iteration Methods - Index page
Fig. 7: Index page

6. Conclusion

In this section, developers learned how to create a simple application with the JavaScript language. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was a beginner’s tutorial to explore the Array Iteration methods in the javascript language.

Download
You can download the full source code of this example here: JavaScript Array Iteration Methods Example

Yatin

The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button