-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendOfLoop.js
More file actions
112 lines (88 loc) · 2.35 KB
/
Copy pathendOfLoop.js
File metadata and controls
112 lines (88 loc) · 2.35 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
var symbolsArr = [
{ symbol: "XFX", price: 240.22, volume: 23432 },
{ symbol: "TNZ", price: 332.19, volume: 234 },
{ symbol: "JXJ", price: 120.22, volume: 5323 }
];
//for each example-> does something to every element of an array
function getStocksymbols(stocks) {
var symbolsArr = [];
stocks.forEach(function(stock) {
symbolsArr.push(stock.symbol);
});
return symbolsArr;
}
console.log(JSON.stringify(getStocksymbols(symbolsArr)));
//map example -> great for transforming all elements of an array and passing to new array
function getStockwithMap(stocks) {
return stocks.map(function(stock) {
return stock.symbol;
});
}
console.log(JSON.stringify(getStockwithMap(symbolsArr)));
//filter example great for applying test to elements of array, and creating array of elements that passed test.
function getStocksOver(stocks, minPrice) {
return stocks.filter(function(stock) {
return stock.price >= minPrice;
});
}
console.log(JSON.stringify(getStocksOver(symbolsArr, 150)));
/*
concat all method flatten array down from one dim to another
*/
var exchanges = [
[
{ symbol: "XFX", price: 240.22, volume: 23432 },
{ symbol: "TNZ", price: 332.19, volume: 234 },
],
[
{ symbol: "JXJ", price: 120.22, volume: 5323 },
{ symbol: "NYN", price: 88.47, volume: 98275 }
]
];
Array.prototype.concatAll = function() {
var results = [];
this.forEach(function(subArray) {
subArray.forEach(function(item) {
results.push(item);
});
});
return results;
};
var stocks = exchanges.concatAll();
stocks.forEach(function(stock) {
console.log(JSON.stringify(stock));
});
// transforming arrays with reduce
var data = [2, 4, 6];
var reducer = function(accumulator, item) {
return accumulator + item;
};
var inititalValue = 0;
var total = data.reduce(reducer, inititalValue);
console.log(total);
/*
reduce object data
*/
var votes = [
"angular",
"angular", ,
"react",
"angular",
"angular",
"react",
"vanilla",
"react",
"ember",
"react"
];
var initVal = {};
var voteReducer = function(tally, vote) {
if (!tally[vote]) {
tally[vote] = 1;
} else {
tally[vote] = tally[vote] + 1;
}
return tally;
};
var result = votes.reduce(voteReducer, initVal);
console.log(result);