function deduplicate(arr, key)?{
return arr.reduce((acc, cur) =>?{
const target = key???cur[key]?: cur;
if (!acc.has(target))?{
acc.set(target, cur);
????}
return acc;
??}, new Map()).values();
}
二、求和;
function?sum(arr,key)?{
????return?arr.reduce((acc,?curr)?=>?acc?+?`${key???curr[key]?:?curr}`,?0);??
}
三、拍平;
function flatten(arr, depth = 1)?{
return arr.reduce((acc, val) =>?{
return acc.concat(depth > 1 && Array.isArray(val)???flatten(val, depth - 1) : val);
??},?[]);
}
const arr =?[[1, 2],?[3, 4],?[5, 6]];
const result = flatten(arr, len);
console.log(result); //?[1, 2, 3, 4, 5, 6];
四、升维;
function chunkArray(arr, len = 2)?{
return arr.reduce((acc, curr, index) =>?{
const chunkIndex = Math.floor(index / len);
if (!acc[chunkIndex])?{
acc[chunkIndex]?=?[];
????}
acc[chunkIndex].push(curr);
return acc;
??},?[]);
}
const arr =?[1, 2, 3, 4, 5, 6];
const result = chunkArray(arr, len);
console.log(result); //?[[1, 2],?[3, 4],?[5, 6]]
五、按条件分组
const groupBy = (arr, key) =>?{
return arr.reduce((acc, curr) =>?{
const key = curr =>?{?return curr[key]};
if (!acc[key])?{
acc[key]?=?[];
????}
acc[key].push(curr);
return acc;
??},?{});
};