复杂的数组分组 JavaScript
javascriptweb developmentfront end technologyobject oriented programming
假设我们有一个像这样的对象数组 −
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 } ]