skip to Main Content

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


  1. 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)

    const num = 1100050010004 
    
    /**
     const {even, odd} = [...String(num)].reduce((acc,curr,i) => {
      acc[i%2===0?'odd':'even']+=(+curr)
      return acc
    },{odd:0,even:0})
    **/
    
    const {even, odd} = [...String(num)].reduce((acc, curr, i) => (acc[i % 2 === 0 ? 'odd' : 'even'] += (+curr), acc), {odd: 0, even: 0});
    
    console.log(even, odd)
    Login or Signup to reply.
  2. You can define a helper function that sum odd or even digits using filter and reduce

    const sumOddOrEven = (num, isEven) => [...String(num)]
      .filter((_, i) => i % 2 === isEven)
      .reduce((acc, val) => acc + (+val), 0);
    
    
    const num = 1100050010004;
    const odd = sumOddOrEven(num, 0);
    const even = sumOddOrEven(num, 1);
    
    console.log(`Odd sum: ${odd}`);
    console.log(`Even sum: ${even}`);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search