数组求和
function sum(arr) {
return arr.reduce(function (val, current, index, arr) {
return val + current;
});
}
数组项相乘
function multi(arr) {
return arr.reduce(function (val, current, index, arr) {
return val * current;
})
}
数组项计数
function itemCounr(arr) {
var counter = {};
return arr.reduce(function (pre, cur, index, arr) {
if (cur in pre) {
pre[cur]++
} else {
pre[cur] = 1;
}
return pre;
}, {})
}
数组项去重
//数组去重
function unsame() {
return arr.reduce(function (pre, cur, index, arr) {
if (!pre.includes(cur)) {
pre.push(cur);
}
return pre;
}, []);
}
多维维数组转一维数组
function toOne(arr) {
return arr.reduce(function (pre, cur, index, arr) {
return Array.isArray(cur) ? pre.concat(toOne((cur))) : pre.concat(cur);
}, []);
};
数组对象指定字段求和
function ObjectSum(arr, field) {
return arr.reduce(function (pre, cur, index, arr) {
return cur[field] + pre;
}, 0)
}
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Reduce</title>
</head>
<body>
<script>
var arr = [1, 2, 3, 4];
function sum(arr) {
return arr.reduce(function (val, current, index, arr) {
return val + current;
});
}
function multi(arr) {
return arr.reduce(function (val, current, index, arr) {
return val * current;
})
}
var arr2 = ['a', 'b', 'c', 'd', 'a', 'c'];
//元素出现次数
function itemCounr(arr) {
var counter = {};
return arr.reduce(function (pre, cur, index, arr) {
if (cur in pre) {
pre[cur]++
} else {
pre[cur] = 1;
}
return pre;
}, {})
}
var arr3 = [1, 2, 3, 4, 2, 2, 1];
//数组去重
function unsame() {
return arr.reduce(function (pre, cur, index, arr) {
if (!pre.includes(cur)) {
pre.push(cur);
}
return pre;
}, []);
}
var arr4 = [[1, 2], [3, 4], [5, 6], [7, 8]];
var arr5 = [[1, [2, 3]], [4, 6], [[6]], [7, 8]];
function toOne(arr) {
return arr.reduce(function (pre, cur, index, arr) {
return Array.isArray(cur) ? pre.concat(toOne((cur))) : pre.concat(cur);
}, []);
};
//对象属性求和
var arr6 = [
{
num: 1
},
{
num: 2
},
{
num:3
}
];
//数组对象字段求和
function ObjectSum(arr, field) {
return arr.reduce(function (pre, cur, index, arr) {
return cur[field] + pre;
}, 0)
}
console.log(sum(arr));
console.log(multi(arr));
console.log(itemCounr(arr2));
console.log(unsame(arr3));
console.log(toOne(arr4));
console.log(toOne(arr5));
console.log(ObjectSum(arr6, 'num'));
</script>
</body>
</html>
网友评论