다음과 같은 객체 배열이 있다고 가정해 보겠습니다. -
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 } ]