I'm starting to code on Javascript and practicing on codewars, I got this problem where I have to find the amount of times the most recurring number is repeated and I do get the correct answer but I also get an "undefined" below the answer and I can't seem to find the reason why... It may be something really simple that I'm missing but I'm stuck here and would appreaciate some help with an explanation.
function mostFrequentItemCount(collection){
let a, b, c = 0, d = 0;
collection.sort((a,b) => a - b)
for (i=0; i<collection.length; i ){
if (collection[i] == collection[i-1]){
b = a = a 1;
if (b>(c && d)){c = i; d = b}
} else {b = a; a = 1}
} console.log(d)
} console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))
And this is the answer we get:
5
undefined
CodePudding user response:
You are getting undefined in this line.
console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3])).
Because mostFrequentItemCount function is not returning any value, hence console.log - prints undefined
CodePudding user response:
You are getting correct result which is 5
from the console.log
which is placed inside the function and getting undefined
from the console.log
where you are calling the function. When the function is getting called and it didn't return any values, it will show as undefined.
You have to return the value from the function so that it will show there also.
function mostFrequentItemCount(collection){
let a, b, c = 0, d = 0;
collection.sort((a,b) => a - b)
for (i=0; i<collection.length; i ){
if (collection[i] == collection[i-1]){
b = a = a 1;
if (b>(c && d)){c = i; d = b}
} else {b = a; a = 1}
} console.log(d) // This is showing the expected output
return d; //This will return the value to where the function called
}
console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))
CodePudding user response:
I already got it right, thanks for everyone feedback, the issue was that I was not returning anything on the function, basically return d fixed it as some of you suggested!
I already updated the code to be accepted on codewars and also replaced d for c since there was not really an use for it.
function mostFrequentItemCount(collection){
if(collection.length == 0) return 0
else{ let a, b, c = 1;
collection.sort((a,b) => a - b)
for (i=0; i<collection.length; i ){
if (collection[i] == collection[i-1]){
b = a = a 1;
if (b >= c){c = b}
} else {b = a; a = 1}
} return c }}
CodePudding user response:
function mostFrequentItemCount(collection){
collection.sort((a,b) => a - b)
let a, b, c , d = 0;
for (i=0; i<collection.length; i ){
if (collection[i] == collection[i-1]){
b = a = a 1;
if (b>(c && d)){c=i; d=b}
} else {b=a; a=1}
} console.log(d)
} console.log(mostFrequentItemCount([3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]))