i have a 13 digit number and want extract odd and even part of this digit. i want to write truth checker function for EAN-13 barcode type that need calculate numbers of my digit.
so i have an digi like this: 1100050010004
i want to get sum of odd and even part of that:
odd parts: 1+0+0+0+1+0+4
even parts: 1+0+5+0+0+0
i think that i must covert digit to array and get odd and even part of that array. this is true and best solution?
i use this method. is this good solution?
var myArr = String(barcode).split("").map((barcode)=>{
return Number(barcode)
});
all_odd = 0;
all_even = 0;
for (var i = 0; i < myArr.length; i++) {
if (i % 2 === 0) all_odd += myArr[i];
else all_even += myArr[i];
}
2
Answers
you can shorten this code with some es6. the logic is essentially converting the number to string and then splitting and then looping (using
reduce
)You can define a helper function that sum odd or even digits using
filter
andreduce