-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path38-map.js
More file actions
40 lines (28 loc) · 938 Bytes
/
Copy path38-map.js
File metadata and controls
40 lines (28 loc) · 938 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// map is very much used in react
// It also takes callback as a parameter like forEach
// but it return a new array of manipulated elements.
/* first way
const numbers = [2, 4, 6, 1, 8];
function squares(number) {
return number * number;
}
const squaredNumbers = numbers.map(squares);
console.log(squaredNumbers);
*/
/* second way - creating function inside map
const numbers = [2, 4, 6, 1, 8];
const output = numbers.map(function (number) {
return number * number;
});
console.log(output);
*/
/* third way - using arrow functions and array objects */
const users = [
{ firstName: "Vaishnao", age: 21 },
{ firstName: "Vaishnavi", age: 22 },
{ firstName: "Arpit", age: 21 },
];
const userNames = users.map((user) => {
return user.firstName; // as map returns an array it is adviced to return the output instead of just logging otherwise it will create an array of undefined objects.
});
console.log(userNames);