簡體   English   中英

如何通過一次迭代檢查數組是否具有多個特定元素?

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

如何通過一次迭代檢查數組是否具有多個特定值 例如,我們有兩個數組:

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

我需要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

要一次性完成,請構建一個結構來跟蹤必須存在的 prop 值(不能丟失)。 遍歷數組並在找到它們時勾選它們。 這在 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))

您可以使用Array.prototype.every() ) 根據您的陣列檢查預先存在的白名單(即testtest1 )。 您可以使用Array.prototype.map()將對象數組轉換為只包含prop值的普通數組,以便於比較:

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

然后,您可以簡單地檢查是否在此映射數組中找到了白名單中的所有元素:

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

請參閱下面的概念驗證:

 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

您可以嘗試使用 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']
    }

它將構建一個像{hasValue1: false, hasValue2: false}這樣的對象,然后為找到的標志返回布爾值 AND。 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