数组常见应用
1、生成类似[1-100]这样的的数组
//大佬写法
const ary = [...Array(100).keys()]
new Array(100) 会生成一个有100空位的数组,这个数组是不能被map(),forEach(), filter(), reduce(), every() ,some()遍历的,因为空位会被跳过(for of不会跳过空位,可以遍历)。 [...new Array(4)] 可以给空位设置默认值undefined,从而使数组可以被以上方法遍历。
2、数组结构赋值的应用
// 交换变量
[a, b] = [b, a]
[o.a, o.b] = [o.b, o.a]
// 生成剩余数组
const [a, ...rest] = [...'asdf'] // a:'a',rest: ["s", "d", "f"]
3、数组浅拷贝
const arr = [1, 2, 3] const arrClone = [...arr]
// 对象也可以这样浅拷贝
const obj = { a: 1 } const objClone = { ...obj }
4、数组去重
const arr = [1, 1, 2, 2, 3, 4, 5, 5]
const newArr = [...new Set(arr)]
new Set(arr)接受一个数组参数并生成一个set结构的数据类型。set数据类型的元素不会重复且是Array Iterator,所以可以利用这个特性来去重。
5、数组合并
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const arr3 = [7, 8, 9]
const arr = [...arr1, ...arr2, ...arr3]
//concat方法也可以
6、数组取交集
const a = [0, 1, 2, 3, 4, 5]
const b = [3, 4, 5, 6, 7, 8]
const duplicatedValues = [...new Set(a)].filter(item => b.includes(item))
console.log(duplicatedValues)// [3, 4, 5]
7、数组转对象
const arr = [1, 2, 3, 4]
const newObj = {...arr} // {0: 1, 1: 2, 2: 3, 3: 4}
const obj = {0: 0, 1: 1, 2: 2, length: 3}
// 对象转数组不能用展开操作符,因为展开操作符必须用在可迭代对象上
let newArr = [...obj] // Uncaught TypeError: object is not iterable...
// 可以使用Array.form()将类数组对象转为数组
let newArr = Array.from(obj) // [0, 1, 2]
8、多维数组转一维数组
二维数组用`array.flat()`,三维及以上用`array.flatMap()`。
let arr = [1,3,[2,[5,6]]]
arr.flat(3) //[1,3,2,5,6]
9、数组摊平
const obj = {a: '群主', b: '男群友', c: '女裙友', d: '未知性别'}
const getName = function (item) { return item.includes('群')}
// 方法1 Object.values(obj) //["群主",男群友,女裙有,未知性别]
const flatArr = Object.values(obj).flat().filter(item => getName(item))
// 经大佬指点,更加简化
const flatArr = Object.values(obj).flat().filter(getName)
10、数组最大最小值
function Max(arr = []) { return arr.reduce((t, v) => t > v ? t : v); }
function Min(arr = []) { return arr.reduce((t, v) => t < v ? t : v); }
const arr = [12, 45, 21, 65, 38, 76, 108, 43];
Max(arr); // 108
Min(arr); // 12
reducu方法()进阶
下面对reduce的语法进行简单说明,详情可看MDN的reduce()的相关说明。
-
定义:对数组中的每个元素执行一个自定义的累计器,将其结果汇总为单个返回值
-
形式:
array.reduce((t, v, i, a) => {}, initValue) -
参数
- callback:回调函数(
必选) - initValue:初始值(
可选)
- callback:回调函数(
-
回调函数的参数
- total(
t):累计器完成计算的返回值(必选) - value(
v):当前元素(必选) - index(
i):当前元素的索引(可选) - array(
a):当前元素所属的数组对象(可选)
- total(
-
过程
- 以
t作为累计结果的初始值,不设置t则以数组第一个元素为初始值 - 开始遍历,使用累计器处理
v,将v的映射结果累计到t上,结束此次循环,返回t - 进入下一次循环,重复上述操作,直至数组最后一个元素
- 结束遍历,返回最终的
t
- 以
reduce的精华所在是将累计器逐个作用于数组成员上,把上一次输出的值作为下一次输入的值。下面举个简单的栗子,看看reduce的计算结果
const arr = [3, 5, 1, 4, 2];
const a = arr.reduce((t, v) => t + v); //15
// 等同于
const b = arr.reduce((t, v) => t + v, 0); //15
高级用法常见场景
1、累加累乘
function Accumulation(...vals) {
return vals.reduce((t, v) => t + v, 0);
}
function Multiplication(...vals) {
return vals.reduce((t, v) => t * v, 1);
}
Accumulation(1, 2, 3, 4, 5); // 15
Multiplication(1, 2, 3, 4, 5); // 120
2、权重求和
const scores = [
{ score: 90, subject: "chinese", weight: 0.5 },
{ score: 95, subject: "math", weight: 0.3 },
{ score: 85, subject: "english", weight: 0.2 } ];
scores.reduce((t,v)=>t+v.score*v.weight,0)
3、 代替reverse
function Reverse(arr=[]){
return arr.reduceRight((t,v)=>(t.push(v), t) ,[])
}
console.log(Reverse([1, 2, 3, 4, 5])) // [5, 4, 3, 2, 1]
4、 代替map和filter
const arr = [0, 1, 2, 3];
// 代替map:[0, 2, 4, 6]
const a = arr.map(v => v * 2);
const b = arr.reduce((t, v) => [...t, v * 2], []);
// 代替filter:[2, 3]
const c = arr.filter(v => v > 1);
const d = arr.reduce((t, v) => v > 1 ? [...t, v] : t, []);
5、 代替some和every
const scores = [
{ score: 45, subject: "chinese" },
{ score: 90, subject: "math" },
{ score: 60, subject: "english" } ];
// 代替some:至少一门合格
const isAtLeastOneQualified = scores.reduce((t, v) => t || v.score >= 60, false); // true
// 代替every:全部合格
const isAllQualified = scores.reduce((t, v) => t && v.score >= 60, true); // false
6、数组过滤
function Difference(arr = [], oarr = []) {
return arr.reduce((t, v) => (!oarr.includes(v) && t.push(v), t), []);
}
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [2, 3, 6]
Difference(arr1, arr2); // [1, 4, 5]
7、*** 数组扁平
function Flat(arr = []) {
return arr.reduce((t, v) => t.concat(Array.isArray(v) ? Flat(v) : v), [])
}
const arr = [0, 1, [2, 3], [4, 5, [6, 7]], [8, [9, 10, [11, 12]]]];
Flat(arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
8、 数组去重
function Uniq(arr = []) {
return arr.reduce((t, v) => t.includes(v) ? t : [...t, v], []);
}
const arr = [2, 1, 0, 3, 2, 1, 2];
Uniq(arr); // [2, 1, 0, 3]
9、 数组成员独立拆解
10、数组成员个数统计
function Count(arr = []) {
return arr.reduce((t, v) => (t[v] = (t[v] || 0) + 1, t), {});
}
const arr = [0, 1, 1, 2, 2, 2];
Count(arr); // { 0: 1, 1: 2, 2: 3 }
11、数组成员位置记录
function Position(arr = [], val) {
return arr.reduce((t, v, i) => (v === val && t.push(i), t), []);
}
const arr = [2, 1, 5, 4, 2, 1, 6, 6, 7];
Position(arr, 2); // [0, 4]
12、数组成员特性分组
function Group(arr = [], key) {
return key ? arr.reduce((t, v) => (!t[v[key]] && (t[v[key]] = []), t[v[key]].push(v), t), {}) : {};
}
const arr = [
{ area: "GZ", name: "YZW", age: 27 },
{ area: "GZ", name: "TYJ", age: 25 },
{ area: "SZ", name: "AAA", age: 23 },
{ area: "FS", name: "BBB", age: 21 },
{ area: "SZ", name: "CCC", age: 19 }
];
// 以地区area作为分组依据
Group(arr, "area"); // { GZ: Array(2), SZ: Array(2), FS: Array(1) }
13、数组成员所含关键字统计
function Keyword(arr = [], keys = []) {
return keys.reduce((t, v) => (arr.some(w => w.includes(v)) && t.push(v), t), []);
}
const text = [
"今天天气真好,我想出去钓鱼",
"我一边看电视,一边写作业",
"小明喜欢同桌的小红,又喜欢后桌的小君,真TM花心",
"最近上班喜欢摸鱼的人实在太多了,代码不好好写,在想入非非"
];
const keyword = ["偷懒", "喜欢", "睡觉", "摸鱼", "真好", "一边", "明天"];
Keyword(text, keyword); // ["喜欢", "摸鱼", "真好", "一边"]
14、字符串翻转
function ReverseStr(str = "") {
return str.split("").reduceRight((t, v) => t + v);
}
const str = "reduce最牛逼";
ReverseStr(str); // "逼牛最ecuder"
15、数字千分化
16、异步累计
async function AsyncTotal(arr = []) {
return arr.reduce(async(t, v) => {
const at = await t;
const todo = await Todo(v);
at[v] = todo;
return at;
}, Promise.resolve({}));
}
const result = await AsyncTotal(); // 需要在async包围下使用
17、URL参数反序列化
function ParseUrlSearch() {
return location.search.replace(/(^?)|(&$)/g, "").split("&").reduce((t, v) => {
const [key, val] = v.split("=");
t[key] = decodeURIComponent(val);
return t;
}, {});
}
// 假设URL为:https://www.baidu.com?age=25&name=TYJ
ParseUrlSearch(); // { age: "25", name: "TYJ" }
18、URL参数序列化
function StringifyUrlSearch(search = {}) {
return Object.entries(search).reduce(
(t, v) => `${t}${v[0]}=${encodeURIComponent(v[1])}&`,
Object.keys(search).length ? "?" : ""
).replace(/&$/, "");
}
StringifyUrlSearch({ age: 27, name: "YZW" }); // "?age=27&name=YZW"
19、返回对象指定键值
function GetKeys(obj = {}, keys = []) {
return Object.keys(obj).reduce((t, v) => (keys.includes(v) && (t[v] = obj[v]), t), {});
}
const target = { a: 1, b: 2, c: 3, d: 4 };
const keyword = ["a", "d"];
GetKeys(target, keyword); // { a: 1, d: 4 }
20、数组转对象
const people = [
{ area: "GZ", name: "YZW", age: 27 },
{ area: "SZ", name: "TYJ", age: 25 }
];
const map = people.reduce((t, v) => { const { name, ...rest } = v; t[name] = rest; return t; }, {});
// { YZW: {…}, TYJ: {…} }
21、reduce性能对比
累加1~100000操作 执行时间
for 6.719970703125ms
forEach 3.696044921875ms
map 3.554931640625ms
reduce 2.806884765625m