1

My question might sound silly but it is fundamental. I am trying to compare the elements of an array and I am getting inaccurate result.

$(document).ready(function(){
   var array =["a","a","a"]
   
   console.log(array[0]===array[1]===array[2])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

why does it return false? What can I do to get the right result?

jason
  • 45
  • 6

3 Answers3

5

Let's break this down...

'a'==='a'==='a'
('a'==='a')==='a'
true==='a'
false

If you want to compare multiple elements in an array to a specific value, I'd recommend the every() method:

var array = ['a', 'a', 'a'];

console.log(array.every((value) => value === 'a'));
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
4

array[0]===array[1] returns true. You then essentially say true===array[2], which is false.

You could say array[0] === array[1] && array[0] === array[2] which I think is logically the same.

Chet
  • 3,461
  • 1
  • 19
  • 24
3

Cause of the problem:

Because:

a === b === c

is the same as:

(a === b) === c

thus you are comparing the result of one comparaison (between a and b) (which will be either true or false) with the last item c.

Solution:

To compare the three items use a logical and operator like this:

a === b && b === c

using logical and to check if a is eqaul to b and if b is equal to c (or if a is equal to c). If one comparaison fail, then the whole test fail, If not then the three items are equal.

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73