Samman Thapa Samman Thapa - 5 months ago 18
Node.js Question

How to create a list of items from another list based on if the items are the key of an object? (Lodash preferred)

How to say this in a more eloquent way, preferably using Lodash:

anObject = {'a': 'apple', 'b': 'banana'};
largeArray = ['a','c','d'];
emptyArray = [];

for(var s = 0; s < largeArray.length; s++){
if(anObject[largeArray[s]]){
emptyArray.push(anObject[largeArray[s]]);
}
}


Should give me:

emptyArray = ['a']

Answer

You can get the intersection() from the largeArray and the keys() from the anObject variable to accomplish this.

_.intersection(largeArray, _.keys(anObject));

var anObject = {'a': 'apple', 'b': 'banana'};
var largeArray = ['a','c','d'];

var emptyArray = _.intersection(largeArray, _.keys(anObject));

console.log(emptyArray);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>