0

I'm trying to create this simple logic whereas I want the array value to add to the previous value. For example the code below, the 18 should carry the 1 and add to the the 9 and the 9 will be 10 then carry the one and add to the 7 and will be 8 and so on. I think I'm on the right track but I can't figure out the rest.

This is for addition math generator I'm working on.

var foo = [7, 9, 18];
var bar =  foo.map(i=>{
  return i % 10
})

console.log(bar) // [7,9,8]  I want it to be [8,0,8]

5 Answers5

0

You have to map with a carry:

  let carry = 0;

  const result = [7, 9, 18].reverse().map(n => {
    n += carry;
    carry = Math.floor(n / 10);
    return n % 10;
 }).reverse();

To extend the result if the carry overflows add:

 if(carry)
   result.unshift(...[...("" + carry)].map(Number));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

You need to iterate the array from the end and reverse the array at start and at the end.

var array = [7, 9, 18],
    result = array
        .reverse()
        .map(
            (carry => value =>
                [carry += value, carry % 10, carry = Math.floor(carry / 10)][1])
            (0)
        )
        .reverse();

console.log(result);

For getting leading carry values, you could use an other approach with Array#reduceRight and some spreading.

var array = [107, 9, 18],
    result = [];

result = [
    ...(array.reduceRight((c, v) => (result.unshift((c += v) % 10), c / 5 >> 1), 0) || '').toString() || [],
    ...result
].map(Number);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Can you change the single characters to full words to make it more readable? – Adam Sep 28 '18 at 17:02
  • This works awesome, thank you so much. except for one thing, if the first number in the array is greater than 10, the script will treat it as a single digit, thus [17, 9, 18] the 1 will be ignored in 17. – Sophek Tounn Sep 28 '18 at 20:50
0

Another way to do this would be this.

const foo = [7, 9, 18];

const func = (arr) => {

    let q = 0;
    
    // Iterate from the end of the array with reduceRight
    
    let toReturn = arr.reduceRight((acc, val) => {
        
        // Add the previous q
        
        val += q;
        
        // Get the next q
        
        q = Math.floor(val / 10);
  
        return acc.concat(val % 10);
    }, []).reverse();
    
    // If there is a q add it to the array
    
    if (q) toReturn = [q, ...toReturn];

    return toReturn;
};

console.log(func(foo));
Alex G
  • 1,897
  • 2
  • 10
  • 15
0

Another way to do it as follows:

This can be achieved by using proper array map syntax. I have modified your code to get expected result. Please find the code below:

var array1 = [7, 9, 18];

const customArr = array1.reverse().map((currentValue, index, arr) => {
    if(index < arr.length)
        arr[index+1] += Math.floor(currentValue / 10);
    return currentValue % 10;
 }).reverse();

console.log(customArr);

I think, this is what you are expecting.

Sandy.....
  • 2,833
  • 2
  • 15
  • 26
  • Thanks so much, this works great, the only thing is if the first number in the Array1 is greater than 10, the script won't account for that, it will treat it like a single number, so 17 will be 7. – Sophek Tounn Sep 28 '18 at 21:11
0

This might not be the most efficient way, in order to get the first number to appear correctly for double digit numbers, I did something like below.

const foo = [17, 9, 18];

const func = (arr) => {

    let q = 0;
    
    // Iterate from the end of the array with reduceRight
    
    let toReturn = arr.reduceRight((acc, val) => {
        
        // Add the previous q
        
        val += q;
        
        // Get the next q
        
        q = Math.floor(val / 10);
  
        return acc.concat(val % 10);
    }, []).reverse();
    
    // If there is a q add it to the array
    
    if (q) toReturn = [q, ...toReturn];
    if (q) {
          let sum = Number(toReturn.slice(0, 2).join(""))
          toReturn.shift();
          toReturn[0] = sum;

          return toReturn
       }
   
    return toReturn;
};

console.log(func(foo));