# How to sort two array of objects using Underscore.js? [closed]

I am sorting 2 arrays of object like this, but I know this is very bad. Any good approach, like using each method like so? ( I tried, but using each, I am unable to return the object )

var O1 = [{'name':'one'}, {'name':'two'}, {'name':'three'}, {'name':'four'}, {'name':'five'}, {'name':'six'}];
var O2 = [{'name':'rat'}, {'name':'cat'}, {'name':'lion'}, {'name':'tiger'}, {'name':'dog'}, {'name':'horse'}];

var sorted1 = _.sortBy(O1, function(item){
return item.name;
})

var sorted2 = _.sortBy(O2, function(item){
return item.name;
})

console.log(sorted1, sorted2);


Demo

Or you can do it without a function at all:

sortBy _.sortBy(list, iterator, [context])

Returns a (stably) sorted copy of list, ranked in ascending order by the results of running each value through iterator. Iterator may also be the string name of the property to sort by (eg. length).

var sorted1 = _.sortBy(O1, 'name'),
sorted2 = _.sortBy(O2, 'name');


There is nothing much inherently wrong with your code besides that you would want to extract that function so that you do not need to declare it twice:

function itemName( item ){
return item.name;
}

var sorted1 = _.sortBy(O1, itemName);
var sorted2 = _.sortBy(O2, itemName);

console.log(sorted1, sorted2);