map an array in javascript

To map an array in JavaScript, you can use the map() function. The map() function creates a new array filled with the results of calling a provided function on every element in the original array.

Here's an example of using map() function to double every element in an array:

index.tsx
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(num) {
  return num * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8, 10]
149 chars
6 lines

In this example, we passed a function to map() that takes an argument num, multiplies it by 2, and returns the result. The map() function then creates a new array doubled with the doubled values.

You can also use an arrow function to make the code shorter:

index.tsx
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
128 chars
4 lines

Here we used an arrow function that takes an argument num, multiplies it by 2, and returns the result. The map() function then creates a new array doubled with the doubled values.

gistlibby LogSnag