简体   繁体   English

将数据排序到范围的 JavaScript 数组

[英]JavaScript array of data sort to range

I am having array of data Ex.我有一组数据 Ex。 var arr = [1,2,3,4,5,7,8,10,11,12,15] . var arr = [1,2,3,4,5,7,8,10,11,12,15] If array of data number sequence match to range like more than two digits.如果数据编号序列数组匹配到超过两位数的范围。 I want to display above array of data as below.我想显示上面的数据数组,如下所示。 result = [1-5,7,8,10-12,15] . result = [1-5,7,8,10-12,15]

Can any one help me how can i achieve above result in JavaScript.任何人都可以帮助我如何在 JavaScript 中实现上述结果。

You could check if a number is in range, the change the last string or push the value to the result set.您可以检查数字是否在范围内,更改最后一个字符串或将值推送到结果集。

 1, 2, 3, 4, 5, 7, 8, 10, 11, 12, 15 ^ no predecessor, push value + ^ + predecessor and successor, change last value + + ^ predecessor and previous predecessor, change last 

 var array = [1, 2, 3, 4, 5, 7, 8, 10, 11, 12, 15], result = []; array.forEach(function (a, i, aa) { result.push(aa[i - 1] + 1 === a && (aa[i - 2] + 1 === aa[i - 1] || a + 1 === aa[i + 1]) ? [result.pop().split('-')[0], a].join('-') : a.toString()); }); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

One way to do it一种方法

 function getRanges(array) { let ranges = [], rstart, rend; for (let i = 0; i < array.length; i++) { rstart = array[i]; rend = rstart; while (array[i + 1] - array[i] == 1) { rend = array[i + 1]; i++; } ranges.push(rstart == rend ? rstart+'' : rstart + '-' + rend); } return ranges; } const range1 = getRanges([1,2,3,4,5,7,8,10,11,12,15]); console.log(range1); const range2 = getRanges([1,2,3,5,7,9,10,11,12,14 ]); console.log(range2); const range3 = getRanges([1,2,3,4,5,6,7,8,9,10]) console.log(range3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM