简体   繁体   English

Lodash从值数组中查找数组中的值

[英]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; 我知道在lodash中,我可以执行以下操作以查找单个值;

_.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 您可以使用some()检查dataLookup一个值是否在data内部,如果是,则返回true ,否则返回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. 您可以使用difference()equal()来检查dataLookup数组中是否存在data数组中的某些值。

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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