Doug Molineux
Doug Molineux

Reputation: 12431

sortBy Lodash isn't sorting correctly

I think I am misunderstanding what is supposed to be happening here. I am trying to sort them by the author property. This is just an abbreviated example that demonstrates my confusion, the actual objects I'm trying to sort are much bigger.

var arr = [ { 
        author: "john" 
    },{ 
        author: "ben" 
    },{ 
        author: "apple" 
    }];

var sortActivities = function (attr, arr) {
    arr = _.sortBy(arr, function(elem){
        return elem[attr];
    });
};
console.log(arr);
sortActivities("author", arr);
console.log(arr);

I expect "apple" to be first in the array after it's been sorted. Please let me know what I'm doing wrong here.

http://jsfiddle.net/1w1ohowm/

Upvotes: 1

Views: 264

Answers (1)

Mattia Franchetto
Mattia Franchetto

Reputation: 349

In you case "arr" is passed by value, so if you wanna get the sorted array you need to return it.

For example, following your code:

var sortActivities = function (attr, arr) {
    return _.sortBy(arr, function(elem){
        return elem[attr];
    });
};
console.log(arr);
arr = sortActivities("author", arr);
console.log(arr);

Hope it helps.

Upvotes: 1

Related Questions