0

can someone explain me, why does javascript return true? The array is global defined.

  console.log(arr[j] + ">" + arr[j + 1]); // 8>50
  console.log(arr[j] > arr[j + 1]);       // true

This happens only for numbers<10, For Example does 22>10 return true.

I need it in my bubbleSort algorithm and fixed this with parseInt(arr[j])>parseInt(arr[j+1]) , but i think there will be better solutions.

Thanks a lot!:)

  • 1
    You have an array of strings – adiga May 06 '21 at 08:45
  • it looks, you are sorting strings. you could take an [unary plus `+`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus) instead of `parseInt` (this requires a base as well for some numbers). – Nina Scholz May 06 '21 at 08:46
  • Thanks a lot @adiga! :) Now i can find a solution! :) – Marvin Ludwig May 06 '21 at 08:47
  • If you want to make it a bit shorter, use the [Unary plus](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus) opeartor: `+arr[j] > +arr[j+1]` – adiga May 06 '21 at 08:49
  • I solved it with a convert from the string array to a array of numbers. `arr = arr.map((arr) => +arr);` – Marvin Ludwig May 06 '21 at 08:53
  • Or use number as a callback to map like this:`arr.map(Number)` – adiga May 07 '21 at 06:52

0 Answers0