0

I have a custom sort function defined & call it as below;

myArr.sort(this.sortArrayBy, key);

sortArrayBy: function(a, b) {

    let param = this.get('sortKey'); //How do I get this value here ? cannot pass it as param OR even access via 'this'

    if (a.param < b.param)
        return -1;
    if (a.param > b.param)
        return 1;
    return 0;
},

I want to pass an additional param inside that function. How do I get access to that class attribute ?

P.S: This code is inside my Ember controller class

2

2 Answers 2

2

You can't make this .sort() take an extra parameter. A workaround is to create a function which wraps a custom defined sort function which does take the additional parameter.


You can define your own sort function which takes an extra parameter:

sortArrayBy: function(a, b, param) {
    // ... sort logic here ...
    return 0;
}

Then, at the point you call myArr.sort, you can define a wrapper to this function which only takes the expected two parameters:

var self = this;
var sortFunc = function(a, b) {
    return self.sortArrayBy(a, b, self.get('sortKey'));  
};
myArr.sort(sortFunc, key);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @testndtv -- I've changed it
Thanks a lot for that...Works like a charm now...Is it possible to customize the sort function further to support both ascending/descending based on 1 param isAscending=true/false ?
Sure -- you're free to change your internal sort function as much as you want. For example, you could multiply the result as follows: return s * (isAscending ? 1 : -1); where s is the value you would have returned normally.
1

You could use a closure over the wanted sort key.

myArr.sort(this.sortArrayBy(key));

sortArrayBy: function (param) {
    return function(a, b) {
        if (a[param] < b[param])
            return -1;
        if (a[param] > b[param])
            return 1;
        return 0;
    };
},

3 Comments

Nina, can you fix the typo on line 5 b.[param] to b[param]. Apparently edits must be at least 6 characters. So I'm not able to make an edit.
param is not available inside the closure...so a[param] & b[param] do not work
please add some data to the question for sorting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.