Comparing identical arrays in Javascript [duplicate] - javascript

This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 7 years ago.
I have two identical array and I want to see if it equals and return true
var a = [1,2];
var b = [1,2];
if (a===b) {
return true
}
these two array are obviously identical but I am getting not equal. Can some explain why and if there is an easy way to compare the two?

Problem is you are creating two different arrays, and === check whether both a and b have same reference. Hence your condition fails. There is no built-in code to compare array, however there are libraries for the same. But you simply write a function to compare the arrays by looping.

1. Don't ever use == operator
It doesn't do what you think and it's quite close to be totally useless (for example "1" == [[1]]). Prefer === instead. If the type is the same for both sides == and === do the same, but if they're not == does crazy conversions you will regret.
2. === for arrays checks identity
I.e. it will return true only if the two sides are the very same object, not an object with the same content (whatever 'same' is meant to be).
If you want to check the content you should first decide how to compare elements... for example
my_eqtest([1, [2, 3]], [1, [2, 3]])
should return true or false?
x = [1, 2]
y = [1, 2]
y.myextramember = "foo"
my_eqtest(x, y) // should be true or false?
You should describe (document) what you mean for equality if it's not object identity, otherwise who reads the code will not understand why something is not working (including yourself in a few weeks).

Easiest way would be use a utility library like lodash _.difference

try this:
function arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
return true;
}

Related

Can typeof Array'instance return ’Array' in JavaScript? [duplicate]

This question already has answers here:
Changing the behaviour of the typeof operator in Javascript
(4 answers)
Closed 3 years ago.
If a is an instance of Array. We know typeof a will returns 'object', but I want to make it return 'array', can I do this?
If I can then how do I do it
If not then why not?
No, you can't - an array is an object, plain and simple:
const aRealArray = [1, 2, 3];
console.log(typeof aRealArray);
You can check if something is an array, however, by using Array.isArray or instanceof
const aRealArray = [1, 2, 3];
console.log(Array.isArray(aRealArray));
console.log(aRealArray instanceof Array);
console.log(Object.prototype.toString.call(aRealArray));
Note that Array.isArray is the more reliable version (and as pointed out by #MattBrowne in the comments below, it works across iframes). instanceof simply checks if Array.prototype is on a prototype chain.
Try using Array's "isArray" method, which returns a boolean:
Array.isArray(a)

Why can't I compare two arrays with "includes"? [duplicate]

This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 3 years ago.
Javascript does not allow comparision of arrays using includes ?
See this example:
let x = [[1,2], [3,4]]
let y = x[0]
let z = [1,2]
console.log(y,z)
// Output: [ 1, 2 ] [ 1, 2 ]
console.log(x.includes(y), x.includes(z))
// Output: true false
I would like to have x.includes(z) to be true.
I was made aware of the qurestion check-if-an-array-contains-any-element-of-another-array-in-javascript by the comments, but it does not answer my question as I want to check if the array has exactly the same elements using includes not only some.
Moreover, this question how-to-compare-arrays-in-javascript does not explain why includes does not work. It tells how to do it, which is not the point of my question.
Because [1, 2] === [1, 2] is false. Different arrays are not equal to each other, not even if they have the same contents. (This is true of all objects.)
You can use includes for the values of the array when they are "primitive types", but not with a whole array.
When you use includes, it checks if the current element of the array is === to the element that is passed as an argument.
In your case, it would be checking if [1,2] === [1,2] this yields false, and it's because via the === comparator you are just checking for the memory reference when applied to arrays.
If you want to do something like comparing for if the whole array is the same probably you are better of using a function like _. isEqual from lodash or implementing your own comparator function.

why does comparing three array elements return false [duplicate]

This question already has answers here:
JavaScript triple equals and three-variable comparison
(2 answers)
Closed 5 years ago.
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?
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'));
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.
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.

Why is [] !== [] in JavaScript? [duplicate]

This question already has answers here:
Why isn't [1,2,3] equal to itself in Javascript? [duplicate]
(6 answers)
Closed 4 years ago.
Why is [] !== [] in JavaScript?
I read through https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness but I could not find anything that explains this.
Edit:
I don't think this question or this question is an exact duplicate of mine. It asks about the == operator which just behaves crazy. The answer is an answer to my question but it's not the same question.
That does a reference check on the two array literals to see if they are the same instance. The fact that you have two literals means that you are constructing two separate arrays, therefore the reference check returns false. This would return true:
var a = []
var b = a
//b === a
This is because we have two references to the same array.
[] creates a new (and empty) array each time you write it. You are comparing two arrays, regardless of their content, their pointer (or reference) are being compared.
var array = [];
var anotherArray = array; // these two will point to the same array, so they are equal
array === anotherArray; // true
array === []; // false
array.push('something');
anotherArray.length; // 1
Because [] is an object, and a comparison of objects only returns true when both sides of the comparison point to the exact same object. You have created two separate objects, so they aren't equal.
var x = []
var y = x
var z = []
x == x // true
x == y // true
x == z // false

how to simplify this statement using indexOf? [duplicate]

This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
Closed 7 years ago.
How can I simplfy the following text inside the if statement in Javascript using "indexof"?
if (a === 1 || a === 2 || a === 3) {
return "correct";
};
I am guessing an array needs to be made for 1,2, and 3, but am unsure of how to us instanceof after that
*edited to say indexOf instead of instanceOf
The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.
In your case, instanceof wont help you. You can use indexOf() with array as follow.
var arr = [1, 2, 3];
// Check if a is present in the arr array
if (arr.indexOf(a) > -1) {
return "correct";
}

Categories

Resources