Search code examples
javascriptarrayslodash

Return true/false for collection of mapped true or false values


I have an array (called acceptedGrades) of accepted "grades". My json returns a grade for each person. This grade must be in the acceptedGrades array TO return true, if not it returns false. Example:

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

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

The next code looks for this to decide if its true or false.

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

Now, the problem is I want to know if ALL items returns true or someone returns false, e.g.

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

I might be going around this the wrong way, and believe there is a simpler way to look at all values of grade as a collect against the acceptedGrades array rather than look at each individual person - any suggestions or answer?


Solution

  • You could wrap the logic inside a method, and actually check if you can found a grade that is not included in the set of valid grades, if you find some item verifying this condition you will know the entire array of items will not be valid:

    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));

    However, it would be more clear if you use every():

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