考虑以下数组:
['a', 'b', 'a'] //method should return true
['a', 'b', 'c'] //method should return true
['a', 'c', 'c'] //method should return false
我想编写一种最有效地检查数组中是否同时存在“ a”和“ b”的方法。我知道我可以在一个简单的for循环中做到这一点
let a_counter = 0;
let b_counter = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] === 'a') {
a_counter++;
}
if (array[i] === 'b') {
b_counter++;
}
}
return (a_counter > 0 && b_counter > 0);
但这不是很短。我可以做indexOf
,但这将循环两次。我还考虑过使用如下设置:
const letter_set = new Set(array)
return (letter_set.has('a') && letter_set.has('b'))
但是我对集合非常陌生,不知道这种解决方案是否可能比循环更昂贵。我知道has()
操作应该比数组迭代更快,但是构造集合可能至少需要O(N)时间(我假设)。
是否有一种干净有效的方法来查找数组中的多个元素? ES6回答欢迎
答案 0 :(得分:3)
您可以仅使用Set
并检查所需项目是否在items数组中。
const
check = (items, wanted) => wanted.every(Set.prototype.has, new Set(items));
console.log(check(['a', 'b', 'a'], ['a', 'b'])); // true
console.log(check(['a', 'b', 'c'], ['a', 'b'])); // true
console.log(check(['a', 'c', 'c'], ['a', 'b'])); // false
答案 1 :(得分:3)
所以我们说每个项目都必须包含在数组中。
constructor(private http: HttpClient, private formBuilder: FormBuilder) {
this.comments = new Array<Comment>();
this.commentFormValidation();
}
ngOnInit() {}
commentFormValidation() {
this.commentForm = this.formBuilder.group({
comment: ['', [Validators.required, Validators.minLength(8)] ]
});
let i=0;
this.posts.forEach(post => {
this.commentForm.addControl('comment'+String(post.post_id),new FormControl(
this.comments[i++],[Validators.required, Validators.minLength(8)]));
});
}
checkForError(post: any){
const inputForm = this.commentForm.get('comment'+post.post_id) ;
if(inputForm.errors && (inputForm.dirty || inputForm.touched )) {
return true;
}
return false;
}
答案 2 :(得分:1)
array.includes('a') && array.includes('b')
includes
似乎是检查特定元素的便捷方法,即使存在多个元素也是如此。
答案 3 :(得分:1)
不像其他示例那样紧凑,但是它确实可以单次运行。
const arr1 = ['a', 'b', 'a']; //method should return true
const arr2 = ['a', 'c', 'c']; //method should return false
const arr3 = ['a', 'b', 'c']; //method should return true
const reducer = ({ a, b }, char) => ({
a: a || char === 'a',
b: b || char === 'b'
});
const includesAnB = arr => {
const { a, b } = arr.reduce(reducer, {});
return a && b;
}
console.log(includesAnB(arr1));
console.log(includesAnB(arr2));
console.log(includesAnB(arr3));