stackunderflow
stackunderflow

Reputation: 1714

Lodash find a value within an array from an array of values

I have the following array:

var data = [
    'Value1',
    'Value2',
    'Value3'
];

Using another array, how would I get a truthy value if a value was found within the data array?

var dataLookup = [
    'Value1',
    'Value2'
]

I know that in lodash I could do the following to look for a single value;

_.includes(data, 'Value1'); // true

I would like to pass an array of values to look for.

Upvotes: 1

Views: 3323

Answers (2)

ryeballar
ryeballar

Reputation: 30088

You can make use of difference() and equal() to check if some values from the data array exists from the dataLookup array.

var found = !_.(data).difference(dataLookup).isEqual(data);

var data = [
    'Value1',
    'Value2',
    'Value3'
];

var dataLookup = [
    'Value1',
    'Value2'
];

var found = !_(data).difference(dataLookup).isEqual(data);

console.log(found);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.js"></script>

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can use some() to check if one value from dataLookup is inside data and if it is it will return true if one isn't it will return false

var data = ['Value1','Value2','Value3'];
var dataLookup = ['Value1','Value2']

var result = dataLookup.some((e) => {return data.indexOf(e) != -1});
console.log(result)

Upvotes: 2

Related Questions