2

i was asked to define a function reduce, that has three parameters, an array, an unknown function, and a number, and reduces the array into a number

and this is was i was given before i was asked to define the function

reduce([1, 2, 3], function(total, number) {

    return total + number;

}, 0); // should return 6

I am a bit clueless on what this is asking me to do to be completely honest

if i could at least get some guideline id be grateful

here is my attempt

var reduce = function(array, func, initial){ 

    function func(){
}

    for( var i = 0; i < array.length; i++){

        func(initial, array[i]);
    }
}
2
  • Please format your code a little better :) Commented Nov 14, 2013 at 5:20
  • 3
    sounds like you're being asked to create Array.prototype.reduce as a static method. Commented Nov 14, 2013 at 5:21

2 Answers 2

1

Try:

function reduce(list, f, acc) {
    return list.length ?
        reduce(list.slice(1), f, f(acc, list[0])) :
        acc;
}

Simple.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to be sure to create a total variable which will be redefined after every function call. You were very close. Try this out:

var reduce = function(array, func, initial){
    var total = initial,
        arr_len = array.length;
    for(var i = 0; i < arr_len; i++){
        total = func(total, array[i]);
    }
};

2 Comments

ha, i think this is what the question was aiming towards. i guess i did not realize how to formulate an unknown function to be called each time. in the exemplary expression above, is total+number representing the parameter function?
Yes. The function takes the current state, total, and changes that state with the current argument of the array (number above). The function you used just increments total.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.