मान लीजिए कि हमारे पास इस तरह की वस्तुओं की एक सरणी है -
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 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 } ]