Problems with sort () and knockoutjs

3

link

I'm having trouble ordering an observableArray of knockoutjs, every time I have to sort the list it gives a revese () effect.

Who does this problem solve?

    
asked by anonymous 11.04.2016 / 11:33

2 answers

1

Well, the parameter a and b of sort is an object, as such you should invoke the function as the number is an observable:)

Here's a working example, I hope you realize what the error was!

link

    
11.04.2016 / 13:10
0

Hello, funcaoDeComparacao(objA, objB) of .sort(funcaoDeComparacao) waits as an integer to return the array order.

If we compare two objects, the comparison rule returns a small number (relative to other comparisons), it will be moved to the beginning of the array.

If the return is a larger number (than the other comparisons), it will be moved to the end of the Array.

So to make it easier to compare objects, we usually return -1 when objA should appear before objB , 0 when objA is equal to objB or 1 when objA should appear after objB .

Note that self.numeros is not an array of integers, but an array of objects of type ranum , which has a property called numero , worth noting that numero is not a integer, but a function that returns one.

Then to perform the ordering of the expected form, do the following:

self.organizar = function() {
  self.numeros.sort(function(a, b) {
    var numeroA = a.numero();
    var numeroB = b.numero();
    return numeroA - numeroB;
  });
}
    
11.04.2016 / 13:58