How to Loop Through Array in jQuery?
Last Updated :
22 Aug, 2024
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
Similar Reads
How to Loop Through an Array in JavaScript?
Here are the various ways to loop through an array in JavaScript1. Using for LoopThe for loop is one of the most used ways to iterate over an array. It gives you complete control over the loop, including access to the array index, which can be useful when you need to modify elements or perform other
4 min read
How to loop through input elements in jQuery ?
In this article, we will learn how to loop through input elements and display their current values in jQuery. This can be done using two approaches: Approach 1: In this approach, we will iterate over every input type which is of text type by using input[type=text] as the selector. Next, we will use
2 min read
How to Loop through JSON in EJS ?
EJS stands for Embedded JavaScript. It is a template engine designed to be used with server-side JavaScript environments like NodeJS and It is used to generate dynamic content in a web page. In this article, we will learn about How to Loop through JSON in EJS with different Approaches. Approaches to
4 min read
How to use array with jQuery ?
An array is a linear data structure. In JavaScript, arrays are mutable lists with a few built-in methods, we can define arrays using the array literal. The arrays can be used in the same way in jQuery as used in JavaScript. Syntax And Declaration:let arr1=[];let arr2=[1,2,3];let arr2=["India","usa",
1 min read
How to check an array is empty or not using jQuery ?
In this article, we will check if an array is empty or not using jQuery. In JavaScript, arrays are a special type of object. If we use the typeof operator for arrays, it returns "object". We can use jQuery's isEmptyObject() method to check whether the array is empty or contains elements. The isEmpty
2 min read
How to iterate through all selected elements into an array ?
The task is to add all the selected HTML elements into an array and iterate through the array. To achieve this, the first step is to select all the desired elements. There are several ways to do this. Finding HTML elements by id:var myElement = document.getElementById("element-id");Finding HTML elem
3 min read
How to use push() & pop() Methods in JavaScript Arrays?
Arrays are dynamic data structures in JavaScript that have the ability to hold several values of various types. The push() and pop() methods are used for adding and removing elements from an array's last index.1. Using push() Method in JavaScriptThe push() method is used to add or push the new value
2 min read
How to Convert List of Elements in an Array using jQuery?
Given an HTML document containing a list of elements, the task is to get the values of the HTML list and convert it into an array using JavaScript. ApproachMake a list(Ordered/ Unordered).Select the parent of <li> element and call an anonymous function for every child of parent( .each() or .ma
2 min read
How to view array of a structure in JavaScript ?
The Javascript arrays are heterogeneous. The structure of the array is the same which is enclosed between two square brackets [ ], and the string should be enclosed between either "double quotes" or 'single quotes'. You can get the structure of by using JSON.stringify() or not, here you will see the
3 min read
How to flatten array with the JavaScript/jQuery?
Flattening an array in JavaScript or jQuery involves transforming a nested array into a single-level array. This process is essential for simplifying complex data structures and making it easier to manipulate and access array elements. Below are the approaches to flatten an array with JavaScript/Jqu
3 min read