Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array containing objects based on another array using _Underscore

I already read the previous questions answered, but it didn't fit with my need.

I have an array of objects such as

var Widgets = [
             [{Id: 'abcdef', post_id: 12345}],
             [{Id: 'ghijkl', post_id: 45678}],
             [{Id: 'mnoptq', post_id: 90123}]
];

I have a second array :

var sortArray = ['ghijkl', 'mnoptq', 'abcdef'];

I need To reorder Widgets with the initial order of elements which appears on sortArray

i've succeed to do it this way

sortArray.forEach(function(Id) {
                    var found = false;                  
                    Widgets = Widgets.filter(function(Widget) {
                        if(!found && Widget.Id == Id) {
                            NewWidgets.push(Widget);
                            found = true;
                            return false;
                        } else {
                            return true;
                        }
                    });
                });

But I wish to improve this code by using _SortBy but I didn't succeed so far...

Anyhelp ?

Edit

Final result should be

var Widgets = [
             [{Id: 'ghijkl', post_id: 45678}],
             [{Id: 'mnoptq', post_id: 90123}],
             [{Id: 'abcdef', post_id: 12345}]
];
like image 577
Toucouleur Avatar asked Feb 23 '15 12:02

Toucouleur


People also ask

How do you sort an array and store it in another array in Java?

You can sort within the array using Arrays. sort() method, or if you want to sort in a different array, you can take following steps: Copy the array to new array. Sort the new array and then sort.

How do I sort two arrays together?

Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list.


1 Answers

Like this?

sorted = _.sortBy(Widgets, function(x) {
    return _.indexOf(sortArray, x[0].Id)
})

This is not very efficient, a faster way is to convert sortArray to an object key=>index and use hash lookups in sortBy:

sortObj = _.invert(_.object(_.pairs(sortArray)));

sorted = _.sortBy(Widgets, function(x) {
    return sortObj[x[0].Id]
})
like image 192
georg Avatar answered Oct 03 '22 14:10

georg