Reputation: 1428
Tell me, how can I optimally convert a string like
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407";
to an array like
const range = [
{
min: 1350,
max: 1350,
},
{
min: 1351,
max: 1351,
},
{
min: 1390,
max: 1391,
},
{
min: 1401,
max: 1401,
},
{
min: 1402,
max: 1407,
},
];
?
In other words, you need to create an array of number ranges using a string in which these numbers ranges are explicitly specified.
The most obvious of the possible algorithms is:
1) split the string using a delimiter,
2) the resulting parts are cleaned of spaces using the command trim
3) check whether the part is a number
4) if not, then split the part using the delimiter -
5) the parts obtained are cleaned of spaces using the command trim
,
6) check that the amount of component eq 2 and it's a number
But is it possible to make it more optimal, more beautiful, more effective?
Upvotes: 0
Views: 173
Reputation: 193301
Try something like this:
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407"
const result = data
.split(/\s*,\s*/)
.map(pair => {
const [min, max = min] = pair
.split(/\s*-\s*/)
.map(Number)
return {
min,
max
}
})
console.log(result)
Upvotes: 2
Reputation: 329
This code will help you.
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407";
var arr = data.split(',');
const range = [];
for(var i=0; i< arr.length; i++){
var b = arr[i].split('-');
if(!b[1])b[1]=b[0];
var obj = new Object();
obj.min = parseInt(b[0]);
obj.max = parseInt(b[1]);
range.push(obj);
}
console.log(range);
Upvotes: 0
Reputation: 30737
I think the simple and much understandable way would be to loop through the values and check if they have a range value (with hyphen) and create the object accordingly for the range
array.
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407";
var range = [];
data.split(',').forEach((val)=>{
var obj = {};
if(val.indexOf('-') === -1 ){
obj.min = val;
obj.max = val;
} else {
obj.min = val.split('-')[0].trim();
obj.max = val.split('-')[1].trim();
}
range.push(obj);
});
console.log(range);
Upvotes: 0
Reputation: 48437
You can use split
method in combination with reduce
method.
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
Also, use +
operator in order to force result to Number
.
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407";
const array = data.split(', ').reduce(function(arr, elem){
var [min, max] = elem.split('-');
arr.push({
min : + min,
max: + (max || min)
});
return arr;
},[]);
console.log(array);
Upvotes: 1
Reputation: 39392
You can use .split()
and .map()
:
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407";
const range = data.split(",").map(s => {
let [min, max = min] = s.split("-");
return {min: Number(min), max: Number(max)}
});
console.log(range);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 5