문제

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;
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top