范围缩小的JavaScript数组 [英] Javascript array of ranges reduction
本文介绍了范围缩小的JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是减少在JavaScript范围的数组尽可能最好的方式。
What is the best possible way to reduce an array of ranges in javascript.
例如我有
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 ?
推荐答案
我首先创建一个没有重复另一个阵列,存储由该范围所覆盖的数字:
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
这篇关于范围缩小的JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文