Daniel Brownlow Daniel Brownlow - 4 months ago 10
Javascript Question

Javascript function explanation - Knockout.js

The other day I asked a question (here). Someone kindly replied, and their answer does what I orginally intended it to do. However, there's some code I don't understand and I was hoping someone could help me.

self.currentlySelected = ko.computed(function() {
return self.topics().reduce(function(count, topic) {
return count + (topic.selected() ? 1 : 0);
}, 0);
});


Would anyone be kind enough to explain what this function is doing? Thank you!

Answer

It is using a reduce method on your list of topics, it is traversing each item in your topics observable array, checking to see if it is selected and then adding all of those up. it could look like this too:

self.currentlySelected = ko.computed(function() {
  var count = 0
  for(var i = 0; i < self.topics().length; i++){
    var topic = self.topics()[i]
    if(topic.selected()){
      count += 1;
    }
  }
  return count
});

the .reduce method is native Javascript method and more can be found Here

the .computed method is knockout.js and is explained pretty well Here