I am working with a result set that consists of various combinations from the following data structure:
[ ["1st", "FELONY"], ["2nd", "FELONY"], ["3rd", "FELONY"], ["1st", "MISDEMEANOR"], ["2nd", "MISDEMEANOR"], ["3rd", "MISDEMEANOR"]]
For example, it could be:
[ ["2nd", "FELONY"], ["2nd", "MISDEMEANOR"], ["1st", "MISDEMEANOR"]]
Or:
[ ["1st", "MISDEMEANOR"], ["2nd", "MISDEMEANOR"]]
Or any other combination and order of elements.
If the array contains a subarray with FELONY, my aim is to disregard MISDEMEANOR elements and retrieve "1st" if available, then "2nd", finally "3rd". If there are no FELONY elements in the array, I want to fetch the "1st" MISDEMEANOR element if present, then "2nd", finally "3rd".
This is how I have approached the problem:
var arr = [ ["1st", "FELONY"], ["3rd", "FELONY"], ["2nd", "FELONY"], ["2nd", "MISDEMEANOR"], ["3rd", "MISDEMEANOR"], ["1st", "MISDEMEANOR"]];
for(var i = 0, found = [], fel1 = false, fel2 = false, fel3 = false, mis1 = false, mis2 = false, mis3 = false; i < arr.length; i++) {
if(arr[i][0] == "1st" && arr[i][1] == "FELONY"){
found = arr[i];
fel1 = true;
} else if (arr[i][0] == "2nd" && arr[i][1] == "FELONY" && !fel1){
found = arr[i];
fel2 = true;
} else if (arr[i][0] == "3rd" && arr[i][1] == "FELONY" && !fel1 && !fel2){
found = arr[i];
fel3 = true;
} else if (arr[i][0] == "1st" && arr[i][1] == "MISDEMEANOR" && !fel1 && !fel2 && !fel3){
found = arr[i];
mis1 = true;
} else if (arr[i][0] == "2nd" && arr[i][1] == "MISDEMEANOR" && !fel1 && !fel2 && !fel3 && !mis1){
found = arr[i];
mis2 = true;
} else if (arr[i][0] == "3rd" && arr[i][1] == "MISDEMEANOR" && !fel1 && !fel2 && !fel3 && !mis1){
found = arr[i];
mis3 = true;
}
}
if( match && (match[2] == "FELONY" || match[2] == "MISDEMEANOR") && (found[2] != "FELONY" && found[1] != "1st") ) {
found = [ match[1], match[2], match[3], match[4] ]
console.log("FOUND! " + found[1]);
} else {
console.log(`could not parse ${chargesList[i]}`);
}
console.log(JSON.stringify(found));
The current solution works but seems a bit messy. Are there cleaner ways to achieve this using EcmaScript 6 features?