Open this example in the interactive library
Source code
const rows = [
{ line: "Red", start: 8, end: 10 },
{ line: "Blue", start: 9, end: 11 },
{ line: "Red", start: 12, end: 15 },
{ line: "Gold", start: 15, end: 16 },
];
const result = [...new Set(rows.map((r) => r.line))]
.map((line) => ({
line,
hours: rows
.filter((r) => r.line === line)
.reduce((sum, r) => sum + r.end - r.start, 0),
}))
.sort((a, b) => b.hours - a.hours);
console.log(JSON.stringify(result, null, 2));
Sample output
[
{
"line": "Red",
"hours": 5
},
{
"line": "Blue",
"hours": 2
},
{
"line": "Gold",
"hours": 1
}
]