-
Notifications
You must be signed in to change notification settings - Fork 0
/
数组去重、扁平.js
55 lines (47 loc) · 1.11 KB
/
数组去重、扁平.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
54
55
/**
* 数组去重
*/
const unique = array => [...new Set(array)];
const unique = array => Array.from(new Set(array));
const unique = array => {
return array.filter((value, key) => array.indexOf(value) === key);
};
const unique = array => {
var container = {};
return array.filter((item, index) =>
container.hasOwnProperty(item) ? false : (container[item] = true)
);
};
/**
* 数组扁平处理
*/
// 基本实现
const flat = array => {
let result = [];
for (let i = 0, len = array.length; i < len; i++) {
if (Array.isArray(array[i])) {
result = result.concat(flat(array[i]));
} else {
result.push(array[i]);
}
}
return result;
};
// reduce 实现
const flat = array =>
array.reduce(
(target, current) =>
Array.isArray(current)
? target.concat(flat(current))
: target.concat(current),
[]
);
// 指定深度
const flattenByDeep = (array, deep = Infinity) =>
array.reduce(
(target, current) =>
Array.isArray(current) && deep > 1
? target.concat(flattenByDeep(current, deep - 1))
: target.concat(current),
[]
);