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
jQuery Tutorial jQuery is a lightweight JavaScript library that simplifies the HTML DOM manipulating, event handling, and creating dynamic web experiences. The main purpose of jQuery is to simplify the usage of JavaScript on websites. jQuery achieves this by providing concise, single-line methods for complex JavaSc
8 min read
Getting Started with jQuery jQuery is a fast lightweight, and feature-rich JavaScript library that simplifies many common tasks in web development. It was created by John Resign and first released in 2006. It makes it easier to manipulate HTML documents, handle events, create animations, and interact with DOM(Document Object M
4 min read
jQuery Introduction jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM). jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser Java
7 min read
jQuery Syntax The jQuery syntax is essential for leveraging its full potential in your web projects. It is used to select elements in HTML and perform actions on those elements.jQuery Syntax$(selector).action()Where - $ - It the the shorthand for jQuery function.(selector) - It defines the HTML element that you w
2 min read
jQuery CDN A Content Delivery Network (CDN) is a system of distributed servers that deliver web content to users based on their geographic location. Including the jQuery CDN in your project can improve the performance, enhance reliability, and simplify maintenance.What is a jQuery CDN?A jQuery CDN is a service
4 min read
jQuery Selectors
JQuery SelectorsWhat is a jQuery Selector?jQuery selectors are functions that allow you to target and select HTML elements in the DOM based on element names, IDs, classes, attributes, and more, facilitating manipulation and interaction. Syntax: $(" ")Note: jQuery selector starts with the dollar sign $, and you encl
5 min read
jQuery * SelectorThe jQuery * selector selects all the elements in the document, including HTML, body, and head. If the * selector is used together with another element then it selects all child elements within the element used. Syntax: $("*")Parameters: *: This parameter is used to select all elements.Example 1: Se
1 min read
jQuery #id SelectorjQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating on the terms, it simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Aja
1 min read
jQuery .class SelectorThe jQuery .class selector specifies the class for an element to be selected. It should not begin with a number. It gives styling to several HTML elements. Syntax: $(".class") Parameter: class: This parameter is required to specify the class of the elements to be selected.Example 1: In this example,
1 min read
jQuery Events
jQuery Effects
jQuery HTML/CSS
jQuery Traversing