男女分组
const users = [
{ name: "Adam", age: 30, sex: "male" },
{ name: "Helen", age: 27, sex: "female" },
{ name: "Amy", age: 25, sex: "female" },
{ name: "Anthony", age: 23, sex: "male" },
];
//男女分组
users.reduce(([one, two], val) =>
val.sex == 'male' ? [[...one, val], two] : [one, [...two, val]]
, [[], []]
);
去重
let arr = [
{age: 1, name: '张三'},
{age: 1, name: '张三'},
{age: 2, name: '李四'},
{age: 3, name: '张三'},];
let arr1 = arr.map(val => val.name);
console.log(arr.filter((val, index) => arr1.indexOf(val.name) === index));
// [ { age: 1, name: '张三' }, { age: 2, name: '李四' } ]
判断两个数组的每个值是否相等
// a是小的,b是大的
const arrayEqual = (a, b) => {
if (!(Array.isArray(a) && Array.isArray(b))) {
return false
}
if (a.length !== b.length||a.length > b.length) {
return false;
}
return a.reduce((acc, val, index) => val === b[index])
};
console.log(arrayEqual([1, 2, 3], [1, 2, 3])); //true
返回数组每一项中最长的那项
['this', 'is', 'a', 'testcase'].reduce(
(acc, val) =>
(acc.length > val.length ? acc : val), 0,
)
// 求和
[1,2,3,4,5].reduce(
(acc,val)=>acc+val,0
)