jquery
  1. jquery-map

jQuery map()

The jQuery map() function is a useful method for manipulating arrays of data and returning a new array with updated values.

Syntax

$(selector).map(function(index, currentvalue))
  • $(selector): The jQuery selector to select the element(s) to be mapped.
  • function(index, currentvalue): The function to be executed for each item in the array.

Use

The map() function can be used to transform data in an array without modifying the original array. It takes an existing array and applies a function to each item in the array, returning a new array with updated values. This can be useful for a variety of tasks, such as parsing data, converting data types, or extracting specific information from an array.

Example

Here is an example of using the map() function to transform an array of numbers into an array of squared numbers:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <script>
    $(document).ready(function(){
      var numbers = [1, 2, 3, 4, 5];
      
      // Use the native JavaScript map function
      var squaredNumbers = $.map(numbers, function(value, index) {
        return value * value;
      });

      // Display the squared numbers in the console for demonstration
      document.write(squaredNumbers);
    });
  </script>
</head>
<body>
  <!-- Body content if needed -->
</body>
</html>
Try Playground

In this example, we use the map() function to square each number in the numbers array. The function is executed for each item in the array, and the returned value is added to a new array, squaredNumbers.

Summary

The map() function in jQuery is a powerful tool for manipulating arrays of data. By applying a function to each item in an array, map() can transform the data into a new array with updated values. This can be used for a wide range of tasks, making it a valuable function to have in your toolkit when working with arrays in JavaScript.

Published on: