Monday, May 20, 2024
61
rated 0 times [  62] [ 1]  / answers: 1 / hits: 72376  / 10 Years ago, sun, june 8, 2014, 12:00:00

I want to do something like this:



var data = [
{
sortData: {a: 'a', b: 2}
},
{
sortData: {a: 'a', b: 1}
},
{
sortData: {a: 'b', b: 5}
},
{
sortData: {a: 'a', b: 3}
}
];

data = _.sortBy(data, [sortData.a, sortData.b]);

_.map(data, function(element) {console.log(element.sortData.a + + element.sortData.b);});


And have it output this:



a 1
a 2
a 3
b 5


Unfortunately, this doesn't work and the array remains sorted in its original form. This would work if the fields weren't nested inside the sortData. How can I use lodash/underscore to sort an array of objects by more than one nested field?



I've turned this into a lodash feature request: https://github.com/lodash/lodash/issues/581


More From » underscore.js

 Answers
4

There is a _.sortByAll method in lodash version 3:



https://github.com/lodash/lodash/blob/3.10.1/doc/README.md#_sortbyallcollection-iteratees



Lodash version 4, it has been unified:



https://lodash.com/docs#sortBy



Other option would be to sort values yourself:



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort



function compareValues(v1, v2) {
return (v1 > v2)
? 1
: (v1 < v2 ? -1 : 0);
};


var data = [
{ a: 2, b: 1 },
{ a: 2, b: 2 },
{ a: 1, b: 3 }
];

data.sort(function (x, y) {
var result = compareValues(x.a, y.a);

return result === 0
? compareValues(x.b, y.b)
: result;
});

// data after sort:
// [
// { a: 1, b: 3 },
// { a: 2, b: 1 },
// { a: 2, b: 2 }
// ];

[#70661] Friday, June 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
calicinthias

Total Points: 447
Total Questions: 101
Total Answers: 118

Location: Botswana
Member since Sat, Dec 31, 2022
1 Year ago
calicinthias questions
Sun, Jan 2, 22, 00:00, 2 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Mon, Aug 10, 20, 00:00, 4 Years ago
;