Reduce应用 (持续更新中)

2023-12-18 19:33:25
  • 一、去重;

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;
??},?{});
};

文章来源:https://blog.csdn.net/weixin_49307011/article/details/135068959
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。