我有三个阵列。
其中一个包含我将要测试的值。另外两个是对象数组,可能包含我在name
键下的第一个数组的值。
const myArray = ["foo", "bar"];
const testArray1 = [
{name: "foo"},
{name: "bar"},
{name: "something else"}
]
const testArray2 = [
{name: "foo"},
{name: "rab"},
{name: "something else"}
]
我正在尝试编写一个条件,只有当测试的数组包含我的第一个数组的所有值时才返回true
。
使用相同的例子,它会给我这样的东西:
if (testArray1.containsAll(myArray)) // true
if (testArray2.containsAll(myArray)) // false
解决此问题的最佳方法是什么?
谢谢,任何帮助非常感谢
答案 0 :(得分:2)
使用array.prototype.every
和array.prototype.find
,它应该是:
const myArray = ["foo", "bar"];
const testArray1 = [
{name: "foo"},
{name: "bar"},
{name: "something else"}
];
const testArray2 = [
{name: "foo"},
{name: "rab"},
{name: "something"}
];
console.log(myArray.every(s => testArray1.find(o => o.name === s)));
console.log(myArray.every(s => testArray2.find(o => o.name === s)));
答案 1 :(得分:2)
可以使用,每一个和一些。这些只返回true / false
const myArray = ["foo", "bar"];
const testArray1 = [
{name: "foo"},
{name: "bar"},
{name: "something else"}
]
const testArray2 = [
{name: "foo"},
{name: "rab"},
{name: "something else"}
]
let result1 = testArray1.every(item => myArray.some(array => item.name == array))
let result2 = testArray2.every(item => myArray.some(array => item.name == array))
console.log('result1', result1)
console.log('result2', result2)

答案 2 :(得分:1)
检查一下。可能不是最好的方式,但工作得很好。
const myArray = ["foo", "bar"];
const testArray1 = [
{name: "foo"},
{name: "bar"},
{name: "something else"}
]
const testArray2 = [
{name: "foo"},
{name: "rab"},
{name: "something else"}
]
let aFlag = testArray1.filter( a => myArray.includes(a.name)).length === myArray.length;
let bFlag = testArray2.filter( a => myArray.includes(a.name)).length === myArray.length;
console.log(aFlag, bFlag)