复杂的数组分组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 }
]热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短