roberto-butti / some-drops-of-javascript

This book collects some useful, unknown, underrated JavaScript functions discovered and learned while using JavaScript daily.
https://drops-of-javascript.hi-folks.dev/
Other
137 stars 40 forks source link

Creating a new mdx for: 02-11 Mapping new array: `map()` #3

Closed roberto-butti closed 11 months ago

roberto-butti commented 1 year ago

Documenting the JavaScript function map()

deshanFdo commented 1 year ago

JavaScript map() Method

The map() method is a built-in function in JavaScript that allows you to create a new array by applying a provided function to each element in an existing array. It does not change the original array but instead returns a new array with the modified elements.

Syntax


array.map(callback(currentValue[, index[, array]])[, thisArg])

- callback: A function that will be called for each element in the array. It takes three arguments: currentValue (the current
- element being processed), index (the index of the current element), and array (the array that map() is being called upon).
   thisArg (optional): Value to use as this when executing callback.

--

Doubling the Elements of an Array:

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((num) => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

------
Extracting Property Values:

const products = [
  { id: 1, name: 'Product A' },
  { id: 2, name: 'Product B' },
  { id: 3, name: 'Product C' }
];

const productNames = products.map((product) => product.name);

console.log(productNames); // Output: ['Product A', 'Product B', 'Product C']

-----
-----

Note:
- The map() method does not mutate the original array. It returns a new array with the modified elements.
- It is called for each element in the array in ascending order.
- The result of map() is a new array of the same length as the original array.
roberto-butti commented 12 months ago

thank you @deshanFdo ! do you want to try to open a PR with these information, or you prefer i open the PR?

Roberto

deshanFdo commented 12 months ago

you can open the PR @roberto-butti .

-sorry for the late response..

roberto-butti commented 11 months ago

Closed with #14