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 JavaScript 1. 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 othe
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 Loop through XML in JavaScript ?
In JavaScript, looping over XML data is important for processing and extracting information from structured XML documents. Below is a list of methods utilized to loop through XML. Table of Content Using for loop with DOMParser and getElementsByTagNameUsing Array.from with DOMParser and childNodesUsi
2 min read
How to Loop Through an Array using a foreach Loop in PHP?
Given an array (indexed or associative), the task is to loop through the array using foreach loop. The foreach loop iterates through each array element and performs the operations. PHP foreach LoopThe foreach loop iterates over each key/value pair in an array. This loop is mainly useful for iteratin
2 min read
How to use push() & pop() 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 valu
2 min read
How to reset Array in PHP ?
You can reset array values or clear the values very easily in PHP. There are two methods to reset the array which are discussed further in this article. Methods: unset() Functionarray_diff() Function Method 1: unset() function: The unset() function is used to unset a specified variable or entire arr
2 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 do you get the length of a string in JQuery?
The task is to get the length of a string with the help of JQuery. We can find the length of the string by the jQuery .length property. The length property contains the number of elements in the jQuery object. Thus it can be used to get or find out the number of characters in a string. Syntax: $(sel
2 min read