Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • jQuery Tutorial
  • jQuery Selectors
  • jQuery Events
  • jQuery Effects
  • jQuery Traversing
  • jQuery HTML & CSS
  • jQuery AJAX
  • jQuery Properties
  • jQuery Examples
  • jQuery Interview Questions
  • jQuery Plugins
  • jQuery Cheat Sheet
  • jQuery UI
  • jQuery Mobile
  • jQWidgets
  • Easy UI
  • Web Technology
Open In App
Next Article:
How to Loop Through Array in jQuery?
Next article icon

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:

Table of Content

  • Using '$.each()' method
  • Using '$.map()' method
  • Using '$.grep()' method
  • Using '$.fn.each()' method
  • Using '$.proxy()' method

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
How to Loop Through Array in jQuery?

M

mathivananshivam
Improve
Article Tags :
  • Web Technologies
  • JQuery
  • jQuery-Questions

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences