0

trying to write a function that takes the change you have in an array [quarters,dimes,nickels,pennies] and second parameter of the cost value n. So ([quarters,dimes,nickels,pennies],n) then I wanna use the reduce method to create an ES6 style of code

I want to understand how to use reduce and grab the second parameter in my code

const changeEnough = ([25, 20, 5, 0], 4.25)
const ct = (accumulator, currentValue) => 
    ((accumulator + currentValue) - intialValue >= 0);

console.log(changeEnough.reduce(ct));

error message I am getting is

changeEnough.reduce is not a function 

I have figured that I am not asking the other value of 4.25 in my code

Stefan Becker
  • 5,201
  • 9
  • 17
  • 27
  • 2
    You're using the comma operator, which has `changeEnough` evaluate to `4.25`, discarding the initial array – CertainPerformance Aug 14 '19 at 05:16
  • Can you elaborate more please? – Tieran Dysart Aug 14 '19 at 05:18
  • 1
    See https://stackoverflow.com/questions/3561043/what-does-a-comma-do-in-javascript-expressions . Don't use the comma operator – CertainPerformance Aug 14 '19 at 05:19
  • Basically `changeEnough` is becoming the number `4.25`, which isn't an array and doesn't contain the `.reduce()` function. Which is why you are getting `changeEnough.reduce is not a function` – Abana Clara Aug 14 '19 at 05:23
  • Also, doing a comparison inside the lambda results in a boolean value instead of a numeric which is then added to a numeric value. You probably want the comparison outside the reduce. – patonw Aug 14 '19 at 05:33

1 Answers1

0

Your declaration of changeEnough is wrong. Using the comma operator like that results in the final value - what actually is it? 4.25:

const changeEnough = ([25, 20, 5, 0], 4.25);
console.log(changeEnough);

So pass the second value as a second argument to reduce. You can make this simple by using an array for changeEnough:

const changeEnough = [[25, 20, 5, 0], 4.25];
const ct = (accumulator, currentValue) => ((accumulator + currentValue) - intialValue >= 0);

console.log(changeEnough[0].reduce(ct, changeEnough[1]));

(Also make sure you've defined initialValue.)

Jack Bashford
  • 38,499
  • 10
  • 36
  • 67