[英]Check if a javascript array contains all elements or part of element values of another array
[英]check if an javascript array contains all of the values of another array
想象你想一个新的字符串( stringB
)出stringA
,当你从stringA的值,它会从stringA消失,不能使用两次。
因此,如果stringB
具有重复值,但stringA
仅具有该值之一,则程序应返回false
。
示例输入:
stringA = "A B C D"
stringB = "B B C D"
示例输出:
false
因为stringA
只有一个“B”。
示例输入:
stringA = "apple banana orange mango"
stringB = "banana orange"
示例输出:
true
这里是我有什么,但它返回true
当它应该已经回到false
谁能告诉我什么是错我的逻辑或如何解决呢? 谢谢!
let arrayContainsArray = (a, b) => { let a_array = a.split(" ") let b_array = b.split(" ") for(let i = 0; i < b_array.length; i++) { if (a_array.includes(b_array[i])) { let index = a_array.indexOf(b_array[i]) a_array.splice(index, 1) } else { return false } return true } } console.log(arrayContainsArray('two times three is not four', 'two times two is four'));
您可以使用every
循环遍历数组并检查条件,并includes
检查数组是否包含某个元素。
let arrayContainsArray = (a, b) => { let a_array = a.split(" ") let b_array = b.split(" ") return a_array.every(o => b_array.includes(o)); } console.log(arrayContainsArray('two times three is not four', 'two times two is four')); console.log(arrayContainsArray('two times two is four', 'two times two is four'));
另一种选择是将b_array
变成一个new Set
。 使用has
检查集合是否包含某个元素。
let arrayContainsArray = (a, b) => { let a_array = a.split(" ") let b_array = b.split(" ") let set = new Set(b_array); return a_array.every(o => set.has(o)); } console.log(arrayContainsArray('two times three is not four', 'two times two is four')); console.log(arrayContainsArray('two times two is four', 'two times two is four'));
您的代码不起作用,因为它在第一次迭代中总是返回任何内容(如果不是 false,则为 true)(原因:return true 语句在 for 循环中)。 尝试这个:
let arrayContainsArray = (a, b) => { let a_array = a.split(" ") let b_array = b.split(" ") for (let i = 0; i < b_array.length; i++) { if (a_array.includes(b_array[i])) { let index = a_array.indexOf(b_array[i]) a_array.splice(index, 1) } else { return false } } return true } console.log(arrayContainsArray('two times three is not four', 'two times two is four')); console.log(arrayContainsArray('ABC D', 'BBC D')); console.log(arrayContainsArray('apple banana orange mango', 'banana orange'));
使用 jquery each 和 inArray 分享我的方法。
// created function
function existAll(baseArray, arrayToCompare) {
var result = true;
$.each(baseArray, function (ix, data) {
if (!($.inArray(data, arrayToCompare) !== -1)) {
result = false;
return false;
}
});
return result;
}
// usage
alert(existAll([1,2,3,4],[1,2,3,5,4]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.