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

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.

Related

Is there a way to splice out elements of an array and return the spliced array in one line? [duplicate]

This question already has answers here:
Js remove element from array without change the original
(4 answers)
Closed 13 days ago.
If I have an array a = [1,2,3,4] and I want to return it with the 3 removed, there are two ways I can do it:
let b = [...a] // or a.slice()
b.splice(2,1)
return b
or
return [...a.slice(0,2), ...a.slice(3,4)]
Advantage of the second is that it's one line. Disadvantage is that it's verbose. I thought of writing a helper function that contains the logic of the first approach, so that I'd be able to call it in one line elsewhere.
Is there an alternative? Something like splice but that returns that spliced array rather than mutating it and returning the spliced-out elements.
Since you know the indicies you want to remove, you can use the Array.prototype.filter method.
const a = [1,2,3,4];
const b = a.filter((_, i) => i !== 2);
console.log(b);
If you need to remove a range, you can just do something like 2 < i || i > 3.
.filter makes a copy of the array, copying the values where the callback function evaluates truthy and ignores the values where the callback function evaluates falsy.

Index of array? [duplicate]

This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Why does this index of a two dimensional array return -1 [duplicate]
(2 answers)
Closed 3 years ago.
I have simple nested array, like:
var arr = [[75.0], [65.0]] ;
and when I do:
arr.indexOf( [75.0] );
I expect 0, but I get -1, what gives?
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf :
indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).
There is the problem. In your example, you have an array of arrays. Comparing with === operator means that for it to evaluate to true, it has to be the same array object. Clearly it is a different object so it is not found from the array.
You need to use Array.find() instead where you can provide the testing function. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

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

Why mapping an array using the same function return in different objects? [duplicate]

This question already has answers here:
How to check if two arrays are equal with JavaScript? [duplicate]
(16 answers)
Closed 6 years ago.
I want to know why v.map(...) is not equal to v.map(...) using the same function to do the map
var v = [1,2,3,4,5]
v.map(function(a) {return a+1}) === v.map(function(a) { return a+1;})
Running this on node repl, I've got the result of the second expression as false
When comparing the equality of non-primitives, Javascript checks equality by equality of reference - that is, do both objects being tested refer to the same object in memory?
In this case, they do not - .map returns a new object, and running .map on the same array two different times will return two different references - regardless of the computations done while mapping.
To sum it all up:
v === v is true because v refers to the same object in memory
[1,2,3,4,5] === [1,2,3,4,5] is false because both arrays are different objects in memory (i.e. reference is compared, not values)
.map will always return a new instance of an array - so the result cannot be equal to another .map statement
This is because arrays are compared by reference, not by value, in Javascript.
In other words, doing something like
[1,2] === [1,2];
returns false in Javascript because the two arrays occupy different locations in memory. They are not compared by the actual contents they may have (which is what we would call comparison by value).
In contrast, doing
var x = [1,2];
x === x;
returns true. In this case, the variable x refers (resolves to the memory location of the array) to the same array and this common reference to a memory location is sufficient to yield true.
map() returns an array. Comparing two arrays by value is a fairly complicated affair in Javascript.

Comparing identical arrays in Javascript [duplicate]

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;
}

Categories

Resources