Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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');
share|improve this answer
add comment

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);
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.