简体   繁体   中英

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.

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) 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM