复杂的数组分组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函数。函数应根据重叠对象的“从”和“到”属性将重叠的对象分组为单个对象,如下所示:
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 }
]热门推荐
6 短祝福语简短暖心
10 发小结婚简短祝福语
11 简短大气的狗年祝福语
12 18岁简短祝福语经典
13 我想找祝福语大全简短
14 祖国生日祝福语简短英文
15 发廊元旦祝福语大全简短
16 生日宝宝祝福语简短独特
17 舅妈生日红包祝福语简短
18 异性朋友简短生日祝福语