复杂的 JavaScript 数组分组


假设我们有一个如下所示的对象数组 -

const arr = [
   {userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 6},
   {userId: "3t5bsFB4PJmA3oTnm", from: 7, to: 15},
   {userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 181},
   {userId: "3t5bsFB4PJmA3oTnm", from: 182, to: 190}
];

我们要求编写一个 JavaScript 函数,该函数取入这样的一个数组。该函数应根据 “from” 和 “to” 属性将重叠的对象分组到一个对象中,如下所示 -

const output = [
   {userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 15},
   {userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 190}
];

示例

const arr = [
   {userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 6},
   {userId: "3t5bsFB4PJmA3oTnm", from: 7, to: 15},
   {userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 181},
   {userId: "3t5bsFB4PJmA3oTnm", from: 182, to: 190}
];
const groupByDuration = (arr = []) => {
   const result = arr.reduce((acc, val) => {
      let last = acc[acc.length - 1] || {};
      if (last.userId === val.userId && last.to + 1 === val.from) {
         last.to = val.to; } else {
            acc.push({ userId: val.userId, from: val.from, to: val.to });
      }
      return acc;
   }, []);
   return result;
}
console.log(groupByDuration(arr));

输出

控制台中的输出为 -

[
   { userId: '3t5bsFB4PJmA3oTnm', from: 1, to: 15 },
   { userId: '3t5bsFB4PJmA3oTnm', from: 172, to: 190 }
]

更新于: 2020-11-21

148 次浏览

开启你的 职业

通过完成课程来获得认证

开始
广告