Winnemucca
Winnemucca

Reputation: 3458

Cannot reduce array inside of an object

I am trying to reduce an array inside of an object. I am getting back

push is not a function 

I have started my array as empty and created a add function to pass in as the first argument.

function add(a,b) {
        return a +b;
}

var navBarArray = [];
var listArray = [];

var mapping = {
  ".navbar": navBarArray,
  ".list-group": listArray
};

I tried this approach on the mapping object but it creates errors

var mapping = {
  ".navbar": Math.round(navBarArray.reduce(add,0) ),
  ".list-group": listArray
};

However, I get push is not a function back in my console.

Below is my function that passes values to the array. I can create a variable inside the function and reduce it there. However, that limits access to my variable and will bloat my function as I continue.

  Object.keys(mapping).forEach(function(selector) { 
      $(selector).hover(function(evt) {
        console.log('mapping',mapping);
        console.log('selector',selector);
        enteredTime = new Date();
      }, function() {
        var ctime = new Date();
        var time = (ctime.getTime() - enteredTime.getTime())/1000;
        mapping[selector].push(time);

        // *********** this works but not where I need it to*******
        var reduce = Math.round(navBarArray.reduce(add,0) );
        console.log(reduce);
        });
    })

Upvotes: 0

Views: 133

Answers (1)

Barmar
Barmar

Reputation: 781310

Change your mapping object so it has separate places for the array and total:

var mapping = {
    ".navbar": {
        total: 0,
        times: []
    },
    ".list-group": {
        total: 0,
        times: []
    }
}

Then you do mapping[selector].times.push(time), and put the total with:

mapping[selector].total = mapping[selector].times.reduce(add, 0);

Upvotes: 2

Related Questions