I'm building an array by passing in individual numbers and ranges of numbers as strings and I want to be able to perform a function on this array and return a comma separated string, firstly by order of the numbers and also grouped if they exist.
For example I have
['13','2','1','7-9','14','3','15-16','20']
And I'd like to be able to get the following result from it:
'1-3,7-9,13-16,20'
This is what I have attempted so far:
function getRangeValues(range)
{
var start = Number(range.split('-')[0]);
var end = Number(range.split('-')[1]);
return Array(end - start + 1).fill().map((_, idx) => start + idx)
}
var splitArray = [];
var originalArray = ['13','2','1','7-9','14','3','15-16','20']
originalArray.forEach(e => {
e.includes('-') ?
splitArray.push(...getRangeValues(e))
: splitArray.push(parseInt(e))
});
splitArray.sort(function(a, b){return a - b});
console.log(splitArray)
// returns [1, 2, 3, 7, 8, 9, 13, 14, 15, 16, 20]
How do I loop through this new array to figure out what ranges exist within it and then return a string showing the ranges and individuals values in ascending order?
For example:
'1-3,7-9,13-16,20'
Via Active questions tagged javascript - Stack Overflow https://ift.tt/KWofAMV
Comments
Post a Comment