Knockout JS: Sorting an observable array of observable numbers

Monday, May 5, 2014

Background


To learn Knockout JS, I'm (slowly) building a gradebook in the browser. My lastest issue involves dropping the lowest scores in an observable array. I have a student model, which has an observable array called scores. This array consists of observable scores, which are plain numbers.


My methodology for removing the lowest grades is as follows. First, I sort each array of scores, high-low, then, for now, splice the end of the array, such that the two lowest numbers are stored into a new array called low. The low variable will be used later when I calculate the mean.


The Problem(s)


First, my current dropLowestGrades method outright removes data from the dom, which I do not desire. Second, myObservableArray.sort() does not appear to do any sorting! I'm not sure where to go here. Relevant script follows.



JSBin: http://ift.tt/1q8IUiW



JS



var StudentsViewModel = (function () {
function StudentsViewModel() {
var _this = this;

...

this.dropLowestScores = function() {
var low = [];
ko.utils.arrayForEach(_this.students(), function(student){
console.log(student.fullName());
student.scores().sort();
/*
student.scores().sort(function(a, b) {
return a() == b() ? 0 : (a() > b() ? 1 : -1);
});
*/
low = student.scores.splice((student.scores().length-2),student.scores().length);
console.log('low: ' + low);
return low;
});
};


HTML


I currently just bind the function to a button. For simplicity's sake, I'm hard-coding the drop to be two scores. I will later allow the user to pass in a value. Note that the button is named "Sort" right now because I was originally going to have a sort feature, then build my dropLowestScores method on top it.



<button data-bind="click: dropLowestScores">Sort</button>






http://ift.tt/1q8IWre