- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray-prototype.js
More file actions
Latest commit
124 lines (99 loc) · 2.76 KB
/
Copy patharray-prototype.js
File metadata and controls
124 lines (99 loc) · 2.76 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
113
114
115
functionfilter(arr,callback){
constnewArray=[];
for(leti=0;i<arr.length;i++){
if(callback(arr[i],i,arr)){
newArray.push(arr[i])
}
}
returnnewArray;
}
functionfilterObject(object,callback){
letnewOject={};
for(constkeyinobject){
if(callback(object[key],key,object)){
newOject={ ...newOject, ...{[key]: object[key]}};
}
}
returnnewOject;
}
// const objFilter = { a: 2, b: 3, c: 4, f: 10 }
// console.log(filterObject(objFilter, (value => value > 3)));
// const arr = [1, 2, 2, 3, 4, 5, 6]
// console.log(filter(arr, (x => x > 3)))
// filter(arr, ((x, i, a) => {
// console.log(i);
// }))
functionmap(array,callback){
constnewArray=[];
for(leti=0;i<array.length;i++){
newArray.push(callback(array[i],i,array))
}
returnnewArray;
}
functionobjectMap(object,callback){
letnewOject={}
for(constkeyinobject){
newOject={ ...newOject, ...{[key]: callback(object[key],key)}}
}
returnnewOject;
}
// const array = [1, 2, 3, 4]
// const array = [{ x: 2, y: 3 }, { x: 2, y: 3 }]
// console.log(map(array, (x => x.x)));
// const obj = { a: 2, b: 3, x: 4 }
// console.log(Object.keys(obj));
// console.log(
// objectMap(obj, ((val, key) => {
// return val * 2;
// }
// ))
// );
functionreduce(array,callback,initialValue){
letaccumulator=initialValue??0;
for(leti=0;i<array.length;i++){
accumulator=callback(accumulator,array[i],i,array)
}
returnaccumulator;
}
functionobjectReduce(object,callback,initialValue){
letaccumulator=initialValue??0;
for(constkeyinobject){
accumulator=callback(accumulator,object[key],key,object);
}
returnaccumulator;
}
// const array = [1, 2, 3, 4]
constobject={a: 2,b: 3,x: 4}
// console.log(reduce(array, ((acc, item) => {
// acc.push()
// }), [] ));
// console.log(
// objectReduce(object, ((acc, value, key) => {
// acc += value;
// return acc;
// }), 0)
// );
// function flat(array, depth = 1) {
// return array.reduce((acc, item) => {
// if (Array.isArray(item)) {
// if (depth >= 1) {
// acc.push(...flat(item, depth - 1))
// return acc;
// }
// }
// acc.push(item)
// return acc;
// }, [])
// }
functionflat(array,depth=1){
returnarray.reduce((acc,item)=>{
if(Array.isArray(item)&&depth>=1){
acc.push(...flat(item,depth-1))
returnacc;
}
acc.push(item);
returnacc;
},[])
}
constarr=[[1,2],3,[8,4,[5,6]]];
console.log(flat(arr));