How to connect to arrays using Lo-Dash

Since I try to use Lo-Dash, I am 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 simple using _.sortBy . But how can you connect?

+7
javascript functional-programming lodash
source share
1 answer

I will need to make a few assumptions to answer your question. First, for example, in the comments for, A2 not valid Javascript. So let go of what Louis offers, and use the format [{ 1: 'val 1' }, ...] instead. Secondly, is there only one key in A2 objects, or do we need to look for them? For simplicity, I'll take the first one.

Given these assumptions, the following will work:

 _.filter(A2, function(d) { return _.contains(A1, _.parseInt(_.keys(d)[0])); }); 

Unlike most of the functions of Lo-dash, those used here do not perform too much abstraction from a simple Javascript dictionary. Given a browser that supports ECMAScript 5, you can replace Lodash wrappers with the following to get the same functionality:

 A2.filter(function(d) { return A1.indexOf(parseInt(Object.keys(d)[0])) !== -1; }); 
+2
source share

All Articles