The Array.prototype.map() function in JavaScript is used to transform the elements of an array into a new array based on a given mapping function. It takes a callback function as its argument, which is executed for each element of the array. The callback function takes three arguments:
- The current element being processed.
- The index of the current element being processed.
- The array map was called upon.
The map() function returns a new array that contains the results of the callback function for each element of the original array.
Here's an example of using the map() function to create a new array with the square of each element of the original array:
In this example, the map() function takes an array of numbers and applies a callback function that squares each number in the array. The result is a new array with the squared values of the original array.
Note that the original array is not modified by the map() function, and the new array returned by map() has the same length as the original array.
const numbers = [1, 2, 3, 4, 5]; const squares = numbers.map((num) => num * num); console.log(squares); // Output: [1, 4, 9, 16, 25]
Mapping an array of strings to an array of their lengths and Mapping an array of numbers to an array of their parity (odd/even)
Mapping an array of strings to an array of their lengths const words = ["hello", "world", "how", "are", "you"]; const lengths = words.map((word) => word.length); console.log(lengths); // Output: [5, 5, 3, 3, 3] Mapping an array of numbers to an array of their parity (odd/even) const numbers = [1, 2, 3, 4, 5]; const parity = numbers.map((num) => (num % 2 === 0 ? "even" : "odd")); console.log(parity); // Output: ["odd", "even", "odd", "even", "odd"]
Mapping an array of objects to an array of their properties
const people = [ { name: "Alice", age: 25 }, { name: "Bob", age: 30 }, { name: "Charlie", age: 35 }, ]; const names = people.map((person) => person.name); console.log(names); // Output: ["Alice", "Bob", "Charlie"] const ages = people.map((person) => person.age); console.log(ages); // Output: [25, 30, 35]