-1
let userInput = [6, '1 6 7 9 10 15'];

let arr = userInput[1].split(" ");

let largest = arr[0];

console.log(arr);
for (let i = 1; i < arr.length; i++) {
  if (arr[i] > largest) {
    largest = arr[i];
  }
}
console.log(largest);

I wanted the largest number to be displayed as 15 but it's showing 9 . Idk why it iterated only till index 3 .

(https://i.stack.imgur.com/hfVZd.jpg)

Joshua
  • 3
  • 1

3 Answers3

1

The reason is numbers in arr array are string and you should parse it in to the Int !

like this :

let userInput = [6, "1 6 7 9 10 15"];

let arr = userInput[1].split(" ");

let largest = parseInt(arr[0]);

console.log(arr);
for (let i = 1; i < arr.length; i++) {
  if (parseInt(arr[i]) > parseInt(largest)) {
    largest = arr[i];
  }
}
console.log(largest);
1

Because you are splitting a string and split(ed) string will result in an array of strings. So basically in your for loop, you are comparing strings instead of integers.

console.log("Welcome to Programiz!");
let userInput = [6, "1 6 7 9 10 15"];

let arr = userInput[1].split(" ").map(Number);

let largest = arr[0];

console.log(arr);
for (let i = 1; i < arr.length; i++) {
  if (arr[i] > largest) {
    largest = arr[i];
  }
}
console.log(largest);

you should be careful here because if the string you are splitting has some elements that can't be converted to Number, it will convert the string to NaN and it might cause bugs in your program.

0
let userInput = [6, '1 6 7 9 10 15'];

let arr = userInput[1].split(" ");

let res = arr.map(e=>parseInt(e))

console.log(Math.max(...res))

If you want max value, it should be answer.

tzztson
  • 328
  • 3
  • 22