Sort an array containing objects based on another array using _Underscore

I already read the answers to previous questions, but this did not meet my needs.

I have an array of objects like

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 that appears in sortArray

I can 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 want to improve this code with _SortBy, but I have not succeeded yet ...

Anyhelp?

Edit

The end result should be

var Widgets = [
             [{Id: 'ghijkl', post_id: 45678}],
             [{Id: 'mnoptq', post_id: 90123}],
             [{Id: 'abcdef', post_id: 12345}]
];
+4
source share
2 answers

Like this?

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

, - sortArray key=>index - sortBy:

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

sorted = _.sortBy(Widgets, function(x) {
    return sortObj[x[0].Id]
})
+4

@georg, , - 1 key/index :

// Example: ['a', 'b', 'c'] becomes { 'a': 0, 'b': 1, 'c': 2 }
var sortObj = sortArray.reduce(function(acc, value, index) {
  acc[value] = index;
  return acc;
}, {});

// Same as posted by @georg, with no need for `parseInt`
sorted = _.sortBy(Widgets, function(Widget) {
  return sortObj[Widget[0].Id];
});

, , , invert/object/pairs.

, parseInt , , .

1. , , .

0

All Articles