Zum Dummi
Zum Dummi

Reputation: 233

how to spread with reduce by recursion

here is for for loop method and the result i want is same like this for the below this code also

function reduce (dollars) {
  let arr = [];
  let change = [10000,5000,2000,1000,500,200,100,50,20,10,1];

  if(dollars === 0) return arr
  for(key of change){
    if(key <= dollars) return arr.concat(key).concat(reduce (dollars -= key));
  }
}

console.log(reduce(900))
console.log(reduce(9000))

how to use reduce and using the spread syntax in recursion way, i got some error and the concat function is called not function when i use reduce by recursively here is the code ,

function reduce(dollar) {
  let change = [10000,5000,2000,1000,500,200,100,50,20,10,1];
  if(dollar === 0) return c
  let c = change.reduce((ar, el) => {
    if(dollar >= el) {
      return ar.concat(el).concat(reduce(dollar-=el))
    }
  }, [])
}
let [ one, two, three] = [10020,9000,900];
console.log(reduce(one));
console.log(reduce(two));
console.log(reduce(three));

the output for the reduce(one) is [ 10000, 20 ]

Upvotes: 4

Views: 145

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30370

Ensure that the reduce handler always returns the array, seeing the handler expects ar to be an array. If undefined is returned in the reduce handler, that will be passed through to the next reduce iteration as ar, which is the cause of the error you're getting.

Also, ensure c is defined before returning it, or revise the code as shown below to avoid the need for c completely:

function reduce(dollar) {

  let change = [10000,5000,2000,1000,500,200,100,50,20,10,1];
  
  /* if dollar === 0 then return [] */
  if (dollar === 0) return [];      
    
  /* Return reduced result (ie "c" in original code) */
  return change.reduce((ar, el) => {
        
    /*
    While el deducted from dollar yields positive value,
    */
    while (dollar - el >= 0) {
      
      /*
      then decrement dollar amout by current el and,
      */
      dollar -= el;  
      
      /*
      add el to current result
      */
      ar = ar.concat(el)
    }
    
    /*
    Return resulting ar array
    */
    return ar;
    
  }, [])
}

let [ one, two, three ] = [ 10020, 9000, 900 ];
console.log(reduce(one));
console.log(reduce(two));
console.log(reduce(three));

Upvotes: 2

Related Questions