Open In App

How to Loop Through Array in jQuery?

Last Updated : 22 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

jQuery offers various methods for looping through arrays, enabling operations like data transformation, filtering, and manipulation. Efficient array iteration is crucial for dynamic web applications and interactive content management.

Below are the approaches to loop through an array in JQuery:

Using $.each() method

  • The $.each() method iterates over arrays or objects, executing a callback function for each item.
  • It takes two arguments: the array (or object) to iterate over and a callback function.
  • The callback function has two parameters: index (the index of the current element) and value (the value of the current element).
  • This method is similar to JavaScript’s native forEach() but includes jQuery-specific enhancements.
  • $.each() provides cross-browser compatibility, addressing inconsistencies in older browsers.

Syntax:

$.each(array, function(index, value) {
// Operation on each element
});

Example: This example uses jQuery's $.each() method to display the index and value of each element in the array within a div element.

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

<head>
    <meta charset="UTF-8">
    <title>jQuery $.each() Example</title>
    <script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
  	</script>
</head>

<body>
    <div id="output"></div>

    <script>
        let myArray = [1, 2, 3, 4, 5];

        $.each(myArray,
            function (index, value) {
                $('#output')
                    .append("Index: " + index +
                        ", Value: " + value + "<br>");
            });
    </script>
</body>

</html>

Output:

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5

Using $.map() method

  • The $.map() method transforms each element in an array and creates a new array based on the provided transformation logic.
  • A callback function is used to define the transformation for each element.
  • Unlike $.each(), which performs actions without returning a result, $.map() returns a new array with the modified elements.
  • It is ideal for scenarios where you need to change or process data and obtain a new array with the results.

Syntax:

$.map(array, function(value, index) {
return transformedValue;
});

Example: This example uses jQuery's $.map() method to double each value in the array, display the original indices and values, and then show the resulting new array.

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

<head>
    <meta charset="UTF-8">
    <title>jQuery $.map() Example</title>
    <script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
  	</script>
</head>

<body>
    <div id="output"></div>

    <script>
        let myArray = [1, 2, 3, 4, 5];

        let newArray =
            $.map(myArray, function (value, index) {
                $('#output')
                    .append("Index: " + index +
                        ", Value: " + value + "<br>");
                return value * 2;
            });

        $('#output')
            .append("New Array: "
                + newArray.join(", ") + "<br>");
    </script>
</body>

</html>

Output:

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5
New Array: 2, 4, 6, 8, 10

Using $.grep() method

  • The $.grep() method filters an array based on a specified condition.
  • A callback function is used to determine which elements meet the condition.
  • It returns a new array containing only the elements that satisfy the condition.
  • It functions similarly to JavaScript’s filter() method.
  • Ideal for removing unwanted elements and extracting a subset of elements that match specific criteria.

Syntax:

$.grep(array, function(value, index) {
return condition;
});

Example: This example uses jQuery's $.grep() method to filter values greater than 2 from the array, display the original indices and values, and then show the filtered array.

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

<head>
    <meta charset="UTF-8">
    <title>jQuery $.grep() Example</title>
    <script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
  	</script>
</head>

<body>
    <div id="output"></div>

    <script>
        let myArray = [1, 2, 3, 4, 5];

        let filteredArray =
            $.grep(myArray,
                function (value, index) {
                    $('#output')
                        .append("Index: " + index +
                            ", Value: " + value + "<br>");
                    return value > 2;
                });

        $('#output')
            .append("Filtered Array: "
                + filteredArray
                    .join(", ") + "<br>");
    </script>
</body>

</html>

Output:

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5
Filtered Array: 3, 4, 5

Using $.fn.each() method

  • Extending the $.fn object allows you to add new functionality to jQuery.
  • Custom methods can be integrated with existing jQuery methods and chained with other functions.
  • This approach enhances code readability, efficiency, and supports modular and scalable development.
  • It makes your jQuery-based codebase more flexible and maintainable.
  • Custom methods can be shared across multiple projects, promoting code reuse and consistency.
  • Building a library of utility functions helps streamline common tasks and improves development speed.

Syntax:

 $(array).each(function(index, value) {
// Operation on each element
});

Example: This example uses jQuery’s $.fn.each() method to iterate over an array and display each index and value in a div element.

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

<head>
    <meta charset="UTF-8">
    <title>jQuery $.fn.each() Example</title>
    <script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
  	</script>
</head>

<body>
    <div id="output"></div>

    <script>
        let myArray = [1, 2, 3, 4, 5];

        $(myArray).each(function (index, value) {
            $('#output')
                .append("Index: "
                    + index + ", Value: " +
                    value + "<br>");
        });
    </script>
</body>

</html>

Output:

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5

Using $.proxy() method

  • The $.proxy() method helps prevent issues with unexpected changes to the this context.
  • It explicitly binds a function to the desired context, maintaining control over function execution.
  • Ensures consistent behavior of functions, especially in asynchronous code or event listeners.
  • Valuable in complex applications with multiple event handlers or nested functions.
  • Helps avoid common pitfalls related to scope and context.
  • Leads to more maintainable and reliable code.

Syntax:

$.proxy(function, context);

Example: This example uses jQuery's $.proxy() method to ensure the multiply function is called with the correct this context, multiplying each array value by a property of an object and displaying the results.

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

<head>
    <meta charset="UTF-8">
    <title>jQuery $.proxy() Example</title>
    <script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
  	</script>
</head>

<body>
    <div id="output"></div>

    <script>
        let myArray = [1, 2, 3, 4, 5];
        let obj = {
            multiplier: 2,
            multiply: function (value) {
                $('#output')
                    .append(value *
                        this.multiplier + "<br>");
            }
        };

        $.each(myArray,
            $.proxy(function (index, value) {
                this.multiply(value);
            }, obj));
    </script>
</body>

</html>

Output:

2
4
6
8
10

Next Article

Similar Reads