I'm trying to see if a value from my data matches against an array of values to return true or false.
Here is what I have come up with so far...
acceptedGrades = ['A1','A2','A3','B1','B2','B3','C1','C2','C3'];
this.state.isValidGrade = _.every(acceptedGrades, d => item.grade === value);
e.g. If item.grade returns A1 grade: 'A1'
return true, if item.grade returns value not in acceptedGrades return false.
I used the same statement to search for a property with hasOwnProperty and thats fine just need to look for the value of a property.
Can use lodash library.
There's a couple of ways to handle that. I think you're after find
, filter
, includes
or findIndex
. every
wouldn't be a good fit here because it's evaluating the whole array to make sure all values satisfy your condition. I think you're just trying to match the grade to an item in the array if I'm understanding correctly.
const acceptedGrades = ['A1','A2','A3','B1','B2','B3','C1','C2','C3'];
// Get first match:
console.log(acceptedGrades.find( g => g === 'B2')); // returns 'B2'
// Get All Matches:
console.log(acceptedGrades.filter( g => g === 'B2')); // returns ['B2']
// Get Index of first match:
console.log(acceptedGrades.findIndex( g => g === 'B2' )); // returns 4
// See if array 'includes' the value
console.log(acceptedGrades.includes('B2')); // returns true