why"indexOf" not working inside nested array?

Tell us what’s happening:

Your code so far


function largestOfFour(arr) {
let a = 0;
for(let i = 0; i < arr.length; i++){
  for(let j = 0; j < arr[i].length; j++){
    let num = arr[i][j];
    
     if(num>a){
      a = num;
     console.log (arr[i][j].indexOf(a));
    }

  }
}

console.log(a)

}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

Hello~!

Try to think about what arr[i][j] represents. What is the value, if you console.log it?

Ya Seems like arr[i] is enough.
but it shows random numbers on arr[i].indexOf(a);

like this

0
1
0
1
0
1
2
3
0
1

why random? it is printing the index of the tested elements (you actually get the same values if you instead print j)

maybe you want to get something else? not an index?

1 Like

I need an index of an array that storing largest number;
where the largest number is now stored inside variable “a”;

you are getting the index then, the biggest number of the first array is at index 1, and that’s the highest number you get before it goes to next array (the 0 is the first index of the new array)

But i need the indexOf a ;
not the largest number.

arr[i].indexOf(a);
where a = 1001;

what you said was correct.
but i need the index of 1001

like this :

console.log (arr[i].indexOf(1001));

on this line

[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]

give

-1
-1
-1
1

so the array with 1 has the largest number!

I don’t get it, what are you asking for?

It is giving you the index of the number you are looking for, or -1 if it is not found.

console.log([1000, 1001, 857, 1].indexOf(1001)); // 1
console.log([1000, 1001, 857, 1].indexOf(42)); // -1
console.log([1000, 1001, 857, 1].indexOf(1)); // 3

I think i just misunderstand the question.

Do you understand what is being asked for though? It kind of seems like it from your initial code.

Try to finish it the way you started. Then my suggestion would be to look at map, Math.max and the ... spread syntax.



1 Like