Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
]Advertisements