Iterating over an array and doing answer validation using AWS Lambda function

45 Views Asked by At

I'm a new dev looking for guidance. I'm writing out an AWS Lambda function for the purpose of array validation. Say I have the first array of

{"food":"ribs", "snacks":"doritos", "drinks":"pepsi"} 

and the second array of

{
  "answer": {
    "food": [
      "ribs",
      "pasta",
      "ramen"
    ],
    "snacks": [
      "doritos",
      "cheetos",
      "popcorn"
    ],
    "drinks": [
      "orange juice",
      "apple juice"
    ]
  }
}

How do I do validation on the first array using the correct answers on the second array?

The validation should return {"true","true","false"}

I'm getting confused on how to start/what method to approach

Any advice is appreciated

1

There are 1 best solutions below

4
Ermi On

You need to lop for the answer key and check with hasOwnProperty() function as follow:

function validateArray(firstArray, secondArray) {
    const validationResults = [];

    // iterate through the keys in the first array
    for (const key in firstArray) {
        // check if the key is present in the second array
        if (secondArray.answer.hasOwnProperty(key)) {
            const validationResult = secondArray.answer[key].includes(firstArray[key]);
            validationResults.push(validationResult);
        } else {
            validationResults.push(false);
        }
    }

    return validationResults;
}

// as you provided
const firstArray = {"food": "ribs", "snacks": "doritos", "drinks": "pepsi"};
const secondArray = {
    "answer": {
        "food": ["ribs", "pasta", "ramen"],
        "snacks": ["doritos", "cheetos", "popcorn"],
        "drinks": ["orange juice", "apple juice"]
    }
};

const result = validateArray(firstArray, secondArray);
console.log(result); // as You needed the output is [true, true, false]