[英]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
与价值test
和test1
,当我把它放在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()
) 根据您的阵列检查预先存在的白名单(即test
和test1
)。 您可以使用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.