假设我们有一个这样的对象数组-
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 } ]