0

I have 2 sets in an array, each of these sets is an array of objects. I'd like to sort both of them using _.each and return a sorted object with the following:

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 sortIt = [O1, O2];

_.each(sortIt, function(item){
    item = _.sortBy(item, function(arr){
        return arr.name;
    })
    return item;
})

console.log(O1, "\n", O2); //nothing changed!

... but, apparently, nothing changes. The question is, what should be the proper approach?

Live Demo

1 Answer 1

2

First and foremost, it's kind of useless checking the values of O1 and O2 variables after the sorting process - they won't change. See, _.sortBy doesn't order the given array in place (as native Array#sort does), instead it returns a new (sorted) copy.

Second, it makes little sense to return anything from _.each iterator function - it'll just be ignored.

Finally, to adjust the specific element of a list, you'll need to address that element; just reassigning some value to a param variable (item in your code) won't be enough.

Here's one approach to do what you want:

var sortIt = [O1, O2];
_.each(sortIt, function(item, index, list) {
    list[index] = _.sortBy(item, function(arr) {
        return arr.name;
    });
})

console.log(sortIt); // something is definitely changed now!

Demo.

Sign up to request clarification or add additional context in comments.

Comments

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.