-
Notifications
You must be signed in to change notification settings - Fork 3
/
42 map() in JS.html
71 lines (63 loc) · 2.74 KB
/
42 map() in JS.html
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<!DOCTYPE html>
<html lang="en">
<head><title>map() in JS</title>
</head>
<body>
<!--
See previous code 41
->map() function: map() function is basically used to transform an array
(means getting new array out of it)
->The map() method is used for creating a new array from an existing one,
by applying a function to each element of the array.
-->
<script>
//example
const arr1=[2,4,6,8];
// these are the some examples of transformations of the arr1:
//double : [4,8,12,16]; //doubles the orginal value
//triple : [6,12,18,24]; //tripes the orginal value etc...
//the things is that if you want to transfromation you do it with the map() function
//syntax: const output=arr1.map(function); //function->which tells what transformation we need to do
//lets try to double the value of arr1
console.log(arr1); //orginal
function double(x){
return x*2; //returns double of x
}
function triple(x){
return x*3
}
const output=arr1.map(double); //double should be a functon
//now this double in map will be run over each and every value of arr1 and creates new array out of it and that new array will be stored inside output
console.log(output);
//lets triple the value of arr1
let output1=arr1.map(triple);
console.log(output1);
//example lets get binary of the array
const num=[1,2,3,4,5,0,10,15];
function ToBinary(x){
//code to get binary of any number
return x.toString(2);
}
const result=num.map(ToBinary); // num.map(ToBinary()); : it won't work
console.log(result);
//we can also put function inside map like this
const arrayChar=['a','e','i','o','u'];
const result1=arrayChar.map(function toUpperCase(x){
return x.toString().toUpperCase();
//or
//return x.toString().toUpperCase().split(",");
});
console.log(result1);
//arrow functions inside map
const arraystr=["JAVASCRIPT"];
const result2=arraystr.map((x)=>{ // or const result2=arrstr.map((x)=>x.toString().toLowerCase());
return x.toString().toLowerCase();
})
console.log(result2);
//square of the array
let arrnum=[1,2,3,4,5,6,7,8,9];
const result3=arrnum.map(x=>x*x);
console.log(result3);
</script>
</body>
</html>