I have few lists like this
a = [ 2, 47-54, 68-69, 120-121, 318, 320, 342, 364-366, 414-422, 503-505, 513-514, 529, 554, 586, 690, 775, 913, 1018, 1117, 1159, 1183, 1218-1219, 1379, 1478, 1491, 1497, 1510, 1562, 1601, 1664, 1673, 1686, 1692, 1710, 1759-1765, 1862-1881, 1951-1962, 1992, 2020 ]
b = [ 18, 28, 34-35, 58-84, 110-137, 139-191, 193-272 ]
value of b = 192
Trying to get a simple javascript code to get the total number of values between different ranges and also add single numbers as I have mentioned for the value of b.
you can do something like this
const b = [ '18', '28', '34-35', '58-84', '110-137', '139-191', '193-272' ]
const calculateTotalNumbers = data => data.reduce((res, n) => {
const [n1, n2] = n.split('-').map(Number)
if(n2){
return res + n2 - n1 + 1
}
return res + 1
}, 0)
console.log(calculateTotalNumbers(b))
You can do it using Array.prototype.reduce.
const
lines = ["18", "28", "34-35", "58-84", "110-137", "139-191", "193-272"],
result = lines.reduce((r, line) => {
const [start, stop = start] = line.split("-").map(Number);
return r + stop - start + 1;
}, 0);
console.log(result);
Note: To handle single lines I've defaulted stop to start.
You can iterate over the values in the array using reduce, splitting values on a - and adding either 1 (when there is no -) or the difference between the end and start values (+1 for inclusive ranges) to the result:
const b = ['18', '28', '34-35', '58-84', '110-137', '139-191', '193-272']
const numsInc = (arr) => arr.reduce((acc, v) => {
[s, e] = v.split('-');
acc += e ? parseInt(e,10)-parseInt(s,10)+1 : 1
return acc;
}, 0)
const numsExc = (arr) => arr.reduce((acc, v) => {
[s, e] = v.split('-');
acc += e ? parseInt(e,10)-parseInt(s,10) : 1
return acc;
}, 0)
console.log(numsInc(b))
console.log(numsExc(b))