1

I wonder what is best and easiest way to get elements by array element from collection - is it possible by using native js?

Here is what is the case:

const ids = [1, 2, 3, 4]
const collection = [{id: 2}, {id: 234}, {id:1}, {id: 345}, {id: 3}, {id:4}, {id:323}];

Expected output should looks like that:

[{id: 1}, {id: 2}, {id: 3}, {id: 4}]

Is there already something built in to lodash? I know we can use filter and indexOf but I wonder what is the shortest and easiest way to do this.

wudoem
  • 15
  • 4

3 Answers3

2

Simple JS

Using filter with the combination of includes

const ids = [1, 2, 3, 4]
const collection = [{id: 2}, {id: 234}, {id:1}, {id: 345}, {id: 3}, {id:4}, {id:323}];

const found = collection.filter(item => ids.includes(item.id));

console.log(found);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

With lodash you can use _.keyBy() to index the collection by id, then get the items by the ids using _.at():

const ids = [1, 2, 3, 4]
const collection = [{id: 2}, {id: 234}, {id:1}, {id: 345}, {id: 3}, {id:4}, {id:323}];

const result = _.at(_.keyBy(collection, 'id'), ids);
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

Since the order of output has to be in sync with ids, use map and find

var output = ids.map( s => collection.find( t => t.id == s ) )

Demo

var ids = [1, 2, 3, 4];
var collection = [{
  id: 2
}, {
  id: 234
}, {
  id: 1
}, {
  id: 345
}, {
  id: 3
}, {
  id: 4
}, {
  id: 323
}];
var output = ids.map(s => collection.find(t => t.id == s));
console.log(output);

In case there are some values in ids which don't have an equivalent value in collection, then use filter after map

var output = ids.map(s => collection.find(t => t.id == s)).filter( s => !!s );

Demo

var ids = [1, 2, 3, 4, 5];
var collection = [{
  id: 2
}, {
  id: 234
}, {
  id: 1
}, {
  id: 345
}, {
  id: 3
}, {
  id: 4
}, {
  id: 323
}];
var output = ids.map(s => collection.find(t => t.id == s)).filter( s => s );
console.log(output);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94