Search code examples
ractivejs

ractivejs list sorting , ascending decending support?


Im trying to understand if there is a feature in ractivejs , for descending sorting , and ascending . I couldnt find anyhting in the documentation .


Solution

  • No - Ractive purposely avoids being a 'kitchen sink' utility library. But it's very easy to add an ascending or descending helper:

    var helpers = Ractive.defaults.data;
    
    // assuming a and b are numbers...
    helpers.ascending = function ( a, b ) {
      return a - b;
    };
    
    helpers.descending = function ( a, b ) {
      return b - a;
    };
    
    ractive = new Ractive({
      el: 'body',
      template: '' +
        '<p>ascending: {{ numbers.slice().sort(ascending) }}</p>' +
        '<p>descending: {{ numbers.slice().sort(descending) }}</p>'
      },
      data: {
        numbers: [ 9, 4, 6, 2, 4, 1, 10, 2, 7, 8 ]
      }
    });
    

    Note that you could also put the ascending and descending functions directly on the data object, if that's preferable.

    Here's a JSFiddle to demonstrate: http://jsfiddle.net/rich_harris/nszt3150/