Complicated array grouping JavaScript


Suppose we have an array of objects like this −

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}
];

We are required to write a JavaScript function that takes in one such array. The function should group overlapping objects based on their "from" and "to" property into a single object like this −

const output = [
   {userId: "3t5bsFB4PJmA3oTnm", from: 1, to: 15},
   {userId: "3t5bsFB4PJmA3oTnm", from: 172, to: 190}
];

Example

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));

Output

And the output in the console will be −

[
   { userId: '3t5bsFB4PJmA3oTnm', from: 1, to: 15 },
   { userId: '3t5bsFB4PJmA3oTnm', from: 172, to: 190 }
]

Updated on: 21-Nov-2020

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements