-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayMethods3.js
53 lines (45 loc) · 1.49 KB
/
ArrayMethods3.js
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
let nums = [23,545,43,657,5645,3243,515,453,54767]
// arr.filter(predicate function())
let newNums = nums.filter((currentValue, index, originalArray) => {
return currentValue > 500
})
console.log(newNums);
// arr.find(predicate function())
let findNums = nums.filter((currentValue, index, originalArray) => {
return currentValue === 515
})
console.log(findNums);
// arr.reduce(predicate function())
let arrr = [1,2,3,4,5,6,7,8,9,10]
let reduced = arrr.reduce((previousVal, currentValue, index, originalArray) => {
previousVal += currentValue
return previousVal
}, 0)
// This function traverses array from left to right
// We can traverse the array from right to left using arr.reduceRight(callback functn())
console.log(reduced);
// arr.reduceRight(predicate function())
let redurcedRight = arrr.reduceRight((previousVal, currentValue, index, originalArray) => {
previousVal += currentValue
return previousVal
}, 0)
console.log(redurcedRight);
// arr.sort() Method
console.log(nums.sort()); // This sorts array only by the first digit
console.log(
nums.sort((a,b) => {
return a = b // this prints same sort by first digit
})
);
// this is needed in cases of strings, alphabetical orders
console.log(
nums.sort((a,b) => {
return a - b // this prints actual sort of numbers
})
);
// This was sort in ascending order, for decending order, just use b - a
console.log(
nums.sort((a,b) => {
return b - a // this prints actual sort of numbers
})
);