Is There A Simple Way To Group Js Array Values By Range?
if I have a js array like below, is there a simple way to re-group the array values by range, the logic is based on the range step, the range step is 1, so if the array values are
Solution 1:
You could use Array#reduce
for it.
var array = ["1", "2", "3", "5", "6", "9", "12", "13", "14", "15", "16"],
result = array.reduce(function (r, a, i, aa) {
r.push(!i || aa[i - 1] - a + 1 ? a : r.pop().split('-')[0] + '-' + a);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Post a Comment for "Is There A Simple Way To Group Js Array Values By Range?"