返回true / false以收集映射的true或false值

时间:2019-01-20 22:45:07

标签: javascript arrays lodash

我有一个接受的“成绩”数组(称为acceptedGrades)。我的json返回每个人的成绩。该成绩必须位于acceptedGrades数组中,以返回true,否则返回false。示例:

acceptedGrades = ['A1','A2','A3','B1','B2','B3','C1','C2','C3'];

for "A1" returns true;
for "Z1" returns false;

下一个代码将对此进行判断,以决定其正确还是错误。

data.map((item) => {
    this.state.isValidGrade = acceptedGrades.includes(item.grade.toUpperCase());
});

现在,问题是我想知道所有项目是否返回true或有人返回false,例如

0:grade: 'B1' //true
1:grade: 'C2' //true
2:grade: 'A3' //true
// All return TRUE so expected result should be TRUE

0:grade: 'B11' //false
1:grade: 'C2' //true
2:grade: 'A3' //true
// Not All return TRUE so the expected result should be FALSE

我可能会以错误的方式解决这个问题,并相信有一种更简单的方法来查看所有等级的值作为对acceptedGrades数组的收集,而不是查看每个人-任何建议或答案?

1 个答案:

答案 0 :(得分:2)

您可以将逻辑包装在一个方法中,并实际检查是否找到了一个grade,但它不包含在有效成绩集中,如果您找到验证此条件的项目,您将知道整个数组项无效:

const acceptedGrades = ['A1','A2','A3','B1','B2','B3','C1','C2','C3'];

// Data examples.

const data1 = [
    {name: "Josh", grade: "B1"},
    {name: "Lucas", grade: "C2"},
    {name: "Damian", grade: "A3"}
];

const data2 = [
    {name: "Josh", grade: "B11"},
    {name: "Lucas", grade: "C2"},
    {name: "Damian", grade: "A3"}
];

// Method that return if a set of grades is valid or not.

const isValidGrade = (data) =>
{
    return !data.find(({grade}) => !acceptedGrades.includes(grade.toUpperCase()));
};

console.log(isValidGrade(data1));
console.log(isValidGrade(data2));

但是,如果您使用every(),则会更清楚:

const isValidGrade = (data) =>
{
    return data.every(({grade}) => acceptedGrades.includes(grade.toUpperCase()));
};