Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array of ranges reduction

What is the best possible way to reduce an array of ranges in javascript.

For example I have

1-3,4-5,10-12,2-4

the result I need for this is

1-5, 10-12

What is the best way to tackle this problem ?

like image 778
Shingala94 Avatar asked Feb 18 '26 03:02

Shingala94


1 Answers

I would first create another array with no duplicates, storing the numbers that are covered by the ranges:

1-3   covers 1, 2, 3    --> [1, 2, 3]
4-5   covers 4, 5       --> [1, 2, 3, 4, 5]
10-12 covers 10, 11, 12 --> [1, 2, 3, 4, 5, 10, 11, 12]
2-4   covers 2, 3, 4    --> [1, 2, 3, 4, 5, 10, 11, 12]

Then, sort the array:

[1, 2, 3, 4, 5, 10, 11, 12] // nothing changed in this example

Finally, rebuild the ranges, depending on the consecutive values:

1-5
10-12
like image 72
sp00m Avatar answered Feb 20 '26 17:02

sp00m