- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayMethods.js
More file actions
Latest commit
80 lines (69 loc) · 2.43 KB
/
Copy pathArrayMethods.js
File metadata and controls
80 lines (69 loc) · 2.43 KB
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
72
73
74
75
76
77
78
79
80
// array.concat() method
letusers=["John","Allen","Boris"]
users=users.concat(["Joe","Anthony","Jacinda"])
console.log(users);
// array.every() method
console.log();
console.log(
users.every(function(currentVal,index,arrr){
console.log(index+" "+arrr);
returntypeof(currentVal)==typeof("")// Type of all values in users is string, so returns true
})
);
// Function passed as parameter to array.every() method contains following:
// function (currentValue, indexOfArray, completeArray) {body}
// Even though console.log statements run like in loop, the return statement returns only one value.
// Runs until condition becomes false, Returns true if all values meet the condition
// array.some() method
console.log();
console.log(
users.some(function(currentVal,index,arrr){
console.log(index+" "+arrr);
returncurrentVal=="Hunter"// If even one values in users is Joe, it returns true
})
);
// Works similar to array.every()
// Returns true even if one value meets the condition
// Convert from other data structure to array
console.log();
letsett=newSet()
sett.add(823)
sett.add(822)
sett.add(7623)
sett.add(5632)
letarrr=Array.from(sett)// Set to Array
console.log(arrr);
console.log(typeof(arrr));
console.log(typeof(sett));
// Type of array, set, map or any data structure in JS is always object
letstr="This is a String!"
console.log(Array.from(str));// Every character, including blank spaces, become elements of array
// Array.isArray()
console.log(Array.isArray(arrr));// This works rather than using typeof()
// Two ways of writing foreach()
console.log();
letresult=""
Array.from(str).forEach(function(currentVal,index,arr){// Method 1: normal function
result=result+currentVal
console.log(index+" - "+result);
})
result=""
console.log();
Array.from(str).forEach((currentVal,index,arr)=>{// Method 2: arrow function
result=result+currentVal
if(index==arr.length-1)
console.log("Sentence - "+result);
})
// array.includes() Method
console.log();
console.log(users.includes("Jacinda"));
console.log(users.includes("Xi"));
// array.indexOf() Method
console.log();
console.log(users.indexOf("Jacinda"));
console.log(users.indexOf("Xi"));// Returns -1 since Xi doesn't exist in array
// array.join() Method
console.log();
console.log(users.join());
console.log(users.join().split(','));
console.log(users.join(" - "));