title: Recreating JavaScript's reduce function
body: <p>I'm trying to recreate the reduce method but as the original function.</p>
  
  <p>This helped me to understand a lot but I have one little issue:
  <a href="https://stackoverflow.com/questions/30277593/how-to-re-create-underscore-js-reduce-method">How to re-create Underscore.js _.reduce method?</a>
  When I plug in arrays it works right, but objects don't work. I get undefined. I would appreciate advice on what I should change. I commented where I think I should change something but I'm confused exactly what I need to change it to. I also created my own each function. </p>
  
  <p>You can find my code here: <a href="http://goo.gl/6RU9Bc" rel="nofollow noreferrer">http://goo.gl/6RU9Bc</a></p>
  
  <p>Any advice would be super helpful. Thank you!!</p>
  
  <p>This is what I have so far:</p>
  
  <pre><code>var myArray=[1,2,3,4,5];
  
  var myObject={
    num1:1,
    num2:2,
    num3:3
  };
  
  function each(collection, callback){
    if(Array.isArray(collection)) {
      for(var i=0, l=collection.length; i&lt;l; i++){
        callback(collection[i]); 
      };
    }else if(collection === "object") {
      for(var prop in collection){
         callback(collection[prop]);
      };
    }
  }
  
  function multiply(num, num2){
    return num*num2;
  }
  
  function reduce(collection, callback, accumulator){
    each(collection, function(element){
      if(accumulator === undefined) {
        return accumulator = element; // is the problem here? Why? I don't understand.
      }else {
        return accumulator = callback(accumulator, element);
      };   
  });
  
  return accumulator;
  };
  
  console.log(reduce(myArray, multiply)); // 120
  console.log(reduce(myArray, multiply, 5)); // 160
  console.log(reduce(myObject, multiply)); // returns undefined
  console.log(reduce(myObject, multiply, 5)); // returns 5
  </code></pre>