0

How to get small and big value from an array using for of loop javascript?

From the code, I able to update the small value. But I am not able update the big value.

const arr = '2 3 1 1 8'.split(" ").map(Number)
let small = arr[0]
let big = arr[0]
for (let i of arr) {
  if (big < arr[i]) {
    big = arr[i]
  }
  if (small > arr[i]) {
    small = arr[i]
  }

}

console.log(small, big)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • `for(let i of arr)` gives you each item in the arra `arr[i`]` takes the value and uses it as an index. For example when `i` is `8` you're looking up `arr[8]` which doesn't exist. – VLAZ Aug 15 '23 at 06:35
  • Either change `of` to `in` or use `i` as a value – Konrad Aug 15 '23 at 06:36

1 Answers1

0

MDN for of

You are using a mix of a for loop and for...of

Solution

const arr = '2 3 1 1 8'.split(" ").map(Number)
let small = arr[0]
let big = arr[0]
for(const element of arr){
        if(big < element){
                big = element
        }
        if(small > element){
                small = element
        }
}

console.log(small, big) // 1 8
p7dxb
  • 397
  • 8