Reputation: 4454
How to efficiently compare 2 pairs of numbers?
Is [a, b] > [c, d]
equivalent to a > c || a === c && b > d
in Javascript?
===========
Edit question: how does Javascript evaluate [a, b] > [c, d]
expression?
Upvotes: 0
Views: 1021
Reputation: 26191
You are trying to do a nested comparison such as on strings. You may simply do like;
[1,3].join() > [1,2].join() // <- true
or ugly but by coercing
[1,3]+"" > [1,2] // <- true
Upvotes: 0
Reputation: 2507
For your problem, you should use the solution you added in your question: a > c || a === c && b > d
, and it is not inefficient at all.
If you are repeating the same task multiple times, then go create a function for it:
function custom_comparison(a, b, c, d) {
return a > c || a === c && b > d;
}
Edit: the first part of my answer was clearly wrong, @rockStar's answer is the correct one in that regard, so I just deleted my explanation.
Upvotes: 0
Reputation:
"Is [a, b] > [c, d] equivalent to a > c || a === c && b > d in Javascript?"
No, the correct results you're getting is because of the single digit numbers you're using. See below.
"how does Javascript evaluate [a, b] > [c, d] expression?"
Because you're not comparing numbers, they two arrays get converted to strings. So substituting the numeric values for the variables, we may get this:
"1,2" > "0,3"
This does work as long as you always have single digit numbers.
Try this:
[10, 2] > [2, 1]
Suddenly it fails. This is because the lexical comparison of "10,2"
and "2,1"
places the second value at a greater position.
Upvotes: 2
Reputation: 386766
You could take a function for an arbitrary length.
function isGreater(aa, b) {
return aa.some((_, i, a) => a[i - 1] === b[i - 1] && a[i] > b[i]);
}
console.log(isGreater([1, 2], [3, 5]));
console.log(isGreater([3, 2], [3, 5]));
console.log(isGreater([3, 6], [3, 5]));
console.log(isGreater([4, 2], [3, 5]));
Upvotes: 0