Looking for some help with a problem as I'm very new to Javascript.
I want to write a function that tallies up feedback scores as shown in the code below. I want to take an array with nested arrays and if the score given is below 3 it should increase the negative
property, if it's in the range 4 - 6 the neutral
property should increase and when it's in the 7 - 10 range, it's positive
that should increase.
I continue to simply receive in the console log
{positive: 0, negative: 0, neutral: 0}
which obviously isn't the expected output. What is wrong?
function gatherFeedback(feedbackArray) {
let result = {
positive: 0,
negative: 0,
neutral: 0
};
if (feedbackArray > 0) {
for (let i = 0; i < feedbackArray; i ) {
if (feedbackArray[i][1] >= 7) {
result.positive
} else if (feedbackArray[i][1] <= 3) {
result.negative
} else if (feedbackArray[i][1] > 3 && feedbackArray < 7) {
result.neutral
}
}
}
return result;
}
console.log(gatherFeedback([
['feedback1', 10],
['feedback2', 3],
['feedback3', 6]
]))
CodePudding user response:
Your main issue is with this line:
if(feedbackArray > 0){
When you try to compare an array to an integer the array first gets converted into a string, which in this case yields:
"feedback1,10,feedback2,3,feedback3,6"
comparing this to 0
yields false
(see the description here as to why) so your loop never runs. The same problem will apply with the next line where you have:
i < feedbackArray
It's simpler just to use a for...of
loop (note you can also simplify your if/else
structure):
function gatherFeedback(feedbackArray) {
let result = {
positive: 0,
negative: 0,
neutral: 0
};
for (let f of feedbackArray) {
if (f[1] >= 7) {
result.positive
} else if (f[1] > 3) {
result.neutral
} else {
result.negative
}
}
return result;
}
console.log(gatherFeedback([
['feedback1', 10],
['feedback2', 3],
['feedback3', 6]
]))
CodePudding user response:
Change your code to this
function gatherFeedback (feedbackArray) {
let result = {positive: 0, negative: 0, neutral: 0};
if(feedbackArray.length > 0){
for(let i = 0; i < feedbackArray.length; i ) {
if(feedbackArray[i][1] >= 7) {
result.positive
} else if(feedbackArray[i][1] <= 3){
result.negative
} else if (feedbackArray[i][1] > 3 && feedbackArray[i][1] < 7) {
result.neutral
}
}
}
return result;
}
CodePudding user response:
Use .length
array property:
function gatherFeedback(feedbackArray) {
let result = {
positive: 0,
negative: 0,
neutral: 0
};
if (feedbackArray.length > 0) {
for (let i = 0; i < feedbackArray.length; i ) {
if (feedbackArray[i][1] >= 7) {
result.positive
} else if (feedbackArray[i][1] <= 3) {
result.negative
} else if (feedbackArray[i][1] > 3 && feedbackArray < 7) {
result.neutral
}
}
}
return result;
}
console.log(gatherFeedback([
['feedback1', 10],
['feedback2', 3],
['feedback3', 6]
]))