Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join arrays using Lo-Dash

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?

like image 744
CalvinDale Avatar asked Mar 08 '14 00:03

CalvinDale


1 Answers

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;
});
like image 139
Yony Avatar answered Nov 09 '22 22:11

Yony