I'm trying to loop through nested arrays to determine if an element in the array is either "open" or "senior":
function openOrSenior(data) {
for (let i = 0; i <= data.length; i++) {
let dataElement = data[i];
for (let j = 0; j <= dataElement.length; j++) {
if (dataElement[0] >= 55 && dataElement[1] > 7) {
return ["Senior"];
}
return ["Open"];
}
}
}
Given the input of
[[18, 20],[45, 2],[61, 12],[37, 6],[21, 21],[78, 9]]
The function should output
["Open", "Open", "Senior", "Open", "Open", "Senior"]
But currently it looks like it's only looping through the first element in the main array ([18, 20]) because my function is only returning:
["Open"]
Why is this function failing to continue to loop through the other nested arrays and return either "Open" or "Senior"? Possibly a problem with the scope?
https://www.codewars.com/kata/categorize-new-member/train/javascript
I was trying to implement what I found here, which suggested a for-loop within a for-loop.
2 Answers 2
You are returning whenever the check succeeds or not, and you've got a redundant for loop. You should iterate the array with a single for loop, and according to the check push Senior or Open to the result array. In the end return the result array.
function openOrSenior(data) {
const result = [];
for (let i = 0; i < data.length; i++) {
const dataElement = data[i];
if (dataElement[0] >= 55 && dataElement[1] > 7) {
result.push("Senior");
} else result.push("Open");
}
return result;
}
console.log(openOrSenior([[18, 20],[45, 2],[61, 12],[37, 6],[21, 21],[78, 9]]));
Or you can use Array.map():
const openOrSenior = data =>
data.map(([a, b]) =>
a >= 55 && b > 7 ? 'Senior' : 'Open'
)
console.log(openOrSenior([[18, 20],[45, 2],[61, 12],[37, 6],[21, 21],[78, 9]]))
Comments
You need only a single loop and an array for the values.
function openOrSenior(data) {
var result = [];
for (let i = 0; i < data.length; i++) {
let [left, right] = data[i];
result.push(left >= 55 && right > 7
? "Senior"
: "Open"
);
}
return result;
}
console.log(openOrSenior([[18, 20], [45, 2], [61, 12], [37, 6], [21, 21], [78, 9]]));
dataElementand you are mentioning them by index, so why the second loop?[Open], though.