简体   繁体   English

如何通过一次迭代检查数组是否具有多个特定元素?

[英]How to check if array has more than one specific element by one iteration?

How to check if array has more than one specific value by one iteration For example, we have two arrays:如何通过一次迭代检查数组是否具有多个特定值 例如,我们有两个数组:

   const arr = [{prop: 'test'}, {prop: "test1"}, {prop: "test3"}];
   const arr2 = [{prop: 'test3'}, {prop: "test"}, {prop: "test2"}];

I need to get true if array object elements have prop with value test and test1 when I put it in if statement for example.I need to get true only if both values exists, If we have not at least one of them I need to get false :我需要true ,如果数组对象元素都有prop与价值testtest1 ,当我把它放在if语句example.I需要得到true只有两个值存在,如果我们还没有它们中的至少一个,我需要得到false

   const arr = [{prop: 'test'}, {prop: "test1"}, {prop: "test3"}]; //true
   const arr2 = [{prop: 'test3'}, {prop: "test"}, {prop: "test2"}]; //false

To do it in a single pass, build a structure that keeps track of the prop values that must be present (must not be missing).要一次性完成,请构建一个结构来跟踪必须存在的 prop 值(不能丢失)。 Run through the array and tick them off as they are found.遍历数组并在找到它们时勾选它们。 This runs in O(n) where n is the length of the big array...这在 O(n) 中运行,其中 n 是大数组的长度......

 // array is a long array of objects // prop is the prop to check in the long array // mustHaves is a short array of values that must be present in prop function check(array, prop, mustHaves) { let missing = {} for (const key of mustHaves) missing[key] = true array.forEach(e => { if (missing[e[prop]]) { missing[e[prop]] = false } }) return Object.values(missing).every(v => !v) } const arr = [{prop: 'test'}, {prop: "test1"}, {prop: "test3"}]; const arr2 = [{prop: 'test3'}, {prop: "test"}, {prop: "test2"}]; const propToCheck = 'prop' const mustHaves = ['test', 'test1'] console.log(check(arr, propToCheck, mustHaves)) console.log(check(arr2, propToCheck, mustHaves))

You can use Array.prototype.every() to check a pre-existing whitelist (ie test and test1 ) against your array.您可以使用Array.prototype.every() ) 根据您的阵列检查预先存在的白名单(即testtest1 )。 You can conver your array of objects objects into plain array that contains just the prop values for easy comparison, using Array.prototype.map() :您可以使用Array.prototype.map()将对象数组转换为只包含prop值的普通数组,以便于比较:

const mappedArray = arr.map(v => v.prop);

And then, you can simply check if all elements in your whitelist is found in this mapped array:然后,您可以简单地检查是否在此映射数组中找到了白名单中的所有元素:

['test', 'test1'].every(x => mappedArray.includes(x));

See proof-of-concept below:请参阅下面的概念验证:

 const arr = [{prop: 'test'}, {prop: "test1"}, {prop: "test3"}]; const arr2 = [{prop: 'test3'}, {prop: "test"}, {prop: "test2"}]; function mustContainValues(arr, whitelist) { const mappedArr = arr.map(v => v.prop); return whitelist.every(x => mappedArr.includes(x)); } console.log(mustContainValues(arr, ['test', 'test1'])); // true console.log(mustContainValues(arr2, ['test', 'test1'])); // false

You can try to build an object using reduce:您可以尝试使用 reduce 构建对象:

   const func = (arr, value1, value2) =>
    {
      let obj = arr.reduce((acc, rec) => {
    if(rec.prop === value1) acc['hasValue1'] = true
    if(rec.prop === value2) acc['hasValue2'] = true
    return acc
    }, {hasValue1: false, hasValue2: false})
    return obj['hasValue1'] && obj['hasValue2']
    }

It will build an object like {hasValue1: false, hasValue2: false} and then return boolean AND for found flags.它将构建一个像{hasValue1: false, hasValue2: false}这样的对象,然后为找到的标志返回布尔值 AND。 Reduce function will iterate through an array only once Invoke this function using: Reduce 函数将仅迭代一次数组使用以下方法调用此函数:

console.log(func(arr, 'test', 'test1'))
console.log(func(arr2, 'test', 'test1'))

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

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