How to access two parameters one being an array the other being a value?

by Tieran Dysart   Last Updated August 14, 2019 05:26 AM - source

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



Answers 1


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
Jack Bashford
August 14, 2019 05:23 AM

Related Questions


Reduce array by its items key in ES6

Updated June 24, 2018 15:26 PM

ES6 Sum by object property in an array

Updated December 13, 2018 03:26 AM

Javascript .map() on copied array

Updated December 29, 2018 02:26 AM