Since I’m trying out Lo-Dash, I’m wondering how to join and sort two arrays?
A1: [ 3, 1 ]
A2: [ { 1: ‘val 1’ }, { 2: ‘val 2’ }, { 3: ‘val 3’ }, { 4: ‘val 4’ }, … ]
A1 join A2 orderBy Vals: [ { 1: ‘val 1’ }, { 3: ‘val 3’ }]
Sorting seems straightforward using _.sortBy
. But how can a join be performed?
I'm going to have to make a few assumptions to answer your question. Firstly, like Louis mentioned in the comments, A2
isn't valid Javascript. So let's go with what Louis suggests and instead use the format [{ 1: 'val 1' }, ...]
. Secondly, are the objects in A2
guaranteed to have only one key, or do we need to search through those? For simplicity I'll assume the former.
Given these assumptions, the following would work:
_.filter(A2, function(d) {
return _.contains(A1, _.parseInt(_.keys(d)[0]));
});
Unlike most of Lo-dash's functions, the ones used here don't perform too much abstraction from plain ol' Javascript. Given a browser that supports ECMAScript 5, you can replace the Lodash wrappers with the following to get the same functionality:
A2.filter(function(d) {
return A1.indexOf(parseInt(Object.keys(d)[0])) !== -1;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With