Compared values have no visual difference with jest - reactjs

I got a problem with my jest/chai unit test.
As you can see I received the same output but the test failed with message: "compared values have no visual difference". How can I fix this?

This is common in javascript. As you probably know already, an array is an object, so I would be explaining using objects.
TLDR: Variable assigned to an object is only a pointer to such value in memory. Hence it is impossible for two variables despite having the different objects containing the same PHYSICAL value but not referring to the same address in memory to be equal.
Javascript compares Objects by identity which means that for the case of the objects a and b below:
Example 1:
a = {name: 'tolumide'}
b = {name: 'tolumide'}
a === b // False
a !== b //True
Although a and b have the same content, there identity differs hence =>
a !== b //True
However, this is different from example 2 below:
Example 2:
c = {name: 'tolumide'}
c = d
c === d // True
c !== d // False
This is because c and d refer to the same value in memory.
What you need is for testing in jest would be something like this:
const expected = ['Alice', 'Bob', 'Eve']
expect.arrayContaining(array)
expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(expected));
OR
const shoppingList = ['beer', 'whiskey']
expect(shoppingList).toContain('beer');
Jest source

Forgive me if I state anything you already know, but the issue appears to be in the underlying object comparison performed by jest.
Array's in javascript are just objects with numbered properties, i.e.
{
0: "value at first index",
1: "value at second index"
}
As such the comparison is done on this underlying object. According to this issue raised by someone on the jest github page, it is possible that the function you are using to create the sorted array is returning a none standard array back, so the comparison fails on the underlying object.
Similar looking issue:
https://github.com/facebook/jest/issues/5998
The solution suggested by one commenter is to Json.Stringify() each array in the test and perform a comparison on that, as this will compare the values themselves.
This is however, as stated "A work around not a fix".
Edit
The stringify option does not work in all cases and should be avoided.
The complete solution for testing if two arrays are equal is found in the first answer to this question: How to check if two arrays are equal with JavaScript?
Disclaimer: Not my code!
function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
// If you don't care about the order of the elements inside
// the array (i.e. [1, 2, 3] == [3, 2, 1]), you should sort both arrays here.
// Please note that calling sort on an array will modify that array.
// you might want to clone your array first.
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}

Related

Accessing an array inside an array

I am new to coding in scala and I am curious about something and it has been hard to find an answer for online. I have this array that takes multiple arguments of different types (:Any)
val arguments= Array("Monday",10,20,Array("test","test2"), if(4 == 4){ "true"})
I iterated and printed the content inside of it. Everything prints properly except the Array at index 3. I get the object memory address I believe, which is understandable-- same thing with Java would happen. But I am curious, how would you access it?
I tried saving the value of arguments(3) in an array (val arr:Array[String] = arguments(3)) but it didn't work because there is a type mismatch (any != Array[String])
Any tips? It might be a gap in my understanding of functional programming.
What you are iterating through is an Array[Any], so you are able to perform functions that are available to an Any type. You can access the items in your array using pattern matching, which uses the unapply methods under the hood to see if it can turn your Any into something more specific:
val arguments= Array("Monday",10,20,Array("test","test2"), if(4 == 4){ "true"})
arguments foreach { arg =>
arg match {
case a:Array[String] => println(s"This is the array: ${a.mkString(",")}, and I can do array functions ${a.contains("test")}")
case _ => println(s"Otherwise I have this: $arg")
}
}
// stdout:
// Otherwise I have this: Monday
// Otherwise I have this: 10
// Otherwise I have this: 20
// This is the array: test,test2, and I can do array functions true
// Otherwise I have this: true

Putting string variables in array, then comparing different string variable value with variable values in array

I have an angular page, with input fields from which I read input values and set them in variables inside .ts file. The values entered may change, so I cant hard-code values.
These are the variables I set values in using [(ngModel)]. All is good with that, values are set.
input1_1: string;
input1_2: string;
input2_1: string;
input2_2: string;
Then I want to make comparison. All the inputs ending with _1 is put in array fromArray, all other, ending with _2 in toArray.
Then I want to make comparison, because I don't want to have a value from fromArray inside toArray.
In a function I tried doing
if (this.toArray.includes(this.input1_1) == true) {
//then disable next button
}
But it doesn't work. I guess I need to get actual values, because it doesn't seem to be checking for actual values.
How can I manage to check if array of variables has same value as a different variables value?
This is all code together (sample from it, as its checking for other things also in the if statement), should make it clearer.
// input values from angular html input fields
input1_1: string;
input1_2: string;
input2_1: string;
input2_2: string;
input3_1: string;
input3_2: string;
input4_1: string;
input4_2: string;
// arrays for checking
fromArray = [this.input1_1, this.input2_1, this.input3_1, this.input4_1];
toArray = [this.input1_2, this.input2_2, this.input3_2, this.input4_2];
// function to run on each input field
checkValues() {
if (this.toArray.includes(this.input1_1) == true) {
this.disableNext = true
} else (this.disableNext = false)
}
I could have just compared values to each other, but I did not want to write too much code, thought this should be a lot shorter.
I've spent last 2 hours searching for similar examples, but none helped.
I did read about array.some(), but It seems that it wouldnt help me, and would cause extra code write, and array.includes() is a better option.
Any tip would be great.
I'm new to coding, so please be gentle and ask for clarification if needed.
EDIT:
As requested by Jo Carrasco and Dev - I will input the whole thing:
StackBlitz link
The html formatting is totally wrong in stackblitz, but it does what is needed.
The this.toArray.includes(this.input1_1) is only in first dropdown function (checkDropDown1) for now, I dont see need to add to others, as I need to check for only one now.
you can see the logic of disabling Next button also - all values needs to be entered if checkbox is checked, and if they are same in either of the places (either 2 dropdowns are same, or any of input fields), the button needs to be disabled.
EDIT 2
It seems that it doesn't update the values in array once they are dynamically changed. It takes the first value the variable had, and saves that value in array, but doesn't change it when and edit happens on the variable (input field).
-- What I did to fix it is I am splicing array value, so that whenever I call a function which should check the values in array, I am deleting and then inserting that value that I need to update into the array and then do a comparison using if statement inside for. Then I do the check inside the actual if statement with equalValue where the original array.include(); was supposed to be.
this.fromArray.splice(0, 1, this.input1_1);
this.toArray.splice(0, 1, this.input1_2);
var equalValue = false;
for (let i = 0; i < this.toArray.length; i++) {
if( this.toArray[i] === this.input1_1) {
equalValue = true;
console.log(this.toArray[i]);
console.log(this.input1_1);
break;
}
}
If you have a better solution, please write it down, I will go through it and mark as answer if it solves the issue better.
Please show the actual code, so we can run it by ourselves.
It looks like those string properties are undefined.
undefined == true //false
So, that's why you can't get the actual value
Try to do it like this
if (this.toArray.includes(this.input1_1)) {
if you really dont care about exact value but toArray and fromArray should not have any value same then here is your solution-
include loadash in your project loadash - https://lodash.com/docs/4.17.15#uniq
checkValues() {
if (_.uniq([...this.toArray, ...this.fromArray]).length < [...this.toArray, ...this.fromArray].length ) {
this.disableNext = true
} else (this.disableNext = false)
}
explanation -
if both array have some values same-
this.toArray = [a,b,c];
this.toArray = [a,b,d];
[...this.toArray, ...this.fromArray] will equal to [a,b,c,a,b,d] // length will be 6
_.uniq([...this.toArray, ...this.fromArray]) will equal to - [a,b,c,d]; // length will be 4
// so if duplicates is present then left hand will be less than right hand in if statement
if both array have no values same
this.toArray = [a,b,c];
this.toArray = [d,g,f];
[...this.toArray, ...this.fromArray] will equal to [a,b,c,d,g,f] // length will be 6
_.uniq([...this.toArray, ...this.fromArray]) will equal to - [a,b,c,d,g,f]; // length will be 6
// so in this case it will go to false condition
hope it helps Happy coding !! :)
What I did to fix it is I am splicing array value, so that whenever I call a function which should check the values in array, I am deleting and then inserting that value that I need to update into the array and then do a comparison using if statement inside for. Then I do the check inside the actual if statement with equalValue where the original array.include(); was supposed to be.
checkValues() {
this.fromArray.splice(0, 1, this.input1_1);
this.toArray.splice(0, 1, this.input1_2);
var equalValue = false;
for (let i = 0; i < this.toArray.length; i++) {
if( this.toArray[i] === this.input1_1) {
equalValue = true;
console.log(this.toArray[i]);
console.log(this.input1_1);
break;
}
}
if (this.equalValue == true) {
this.disableNext = true
} else (this.disableNext = false)
}
If you have a better solution, please write it down, I will go through it and mark as answer if it solves the issue better.

Ensuring Object does not exist in Array [duplicate]

This question already has answers here:
Javascript: Using `.includes` to find if an array of objects contains a specific object
(7 answers)
Closed 23 days ago.
I'm attempting to find an object in an array using Array.prototype.includes. Is this possible? I realize there is a difference between shallow and deep comparison. Is that the reason the below code returns false? I could not find a relevant answer for Array.includes().
Array.includes compares by object identity just like obj === obj2, so sadly this doesn't work unless the two items are references to the same object. You can often use Array.prototype.some() instead which takes a function:
const arr = [{a: 'b'}]
console.log(arr.some(item => item.a === 'b'))
But of course you then need to write a small function that defines what you mean by equality.
Its' because both of the objects are not the same. Both are stored at different place in memory and the equality operation results false.
But if you search for the same object, then it will return true.
Also, have a look at the below code, where you can understand that two identical objects also results false with the === operator.
For two objects to return true in ===, they should be pointing to same memory location.
This is because the includes checks to see if the object is in the array, which it in fact is not:
> {a: 'b'} === {a: 'b'}
false
This is because the test for equality is not testing if the objects are the same, but whether the point to the same object. Which they don't.
You are on the right track but, the issue is the difference between reference and value types, you currently are using a reference type (object literal), so when you compare what is in the array with what you have, it will compare the references and not the values. this is what I mean:
var ar = [];
var x = {a: "b", c: "d" };
ar.push(x);
// this will log true because its the same reference
console.log("should be true: ", ar[0] === x);
ar.push({a: "b", c: "d" });
// this will log false because i have created
// a different reference for a new object.
console.log("should be false: ", ar[1] === x);
// Think of it like this
var obja = { foo: "bar" }; // new reference to 'obja'
var objb = { foo: "bar" }; // new reference to 'objb'
var valuea = 23;
var valueb = 23;
// 'obja' and 'obja' are different references
// although they contain same property & value
// so a test for equality will return false
console.log("should be false: ", obja === objb);
// on the other hand 'valuea' and 'valueb' are
// both value types, so an equality test will be true
console.log("should be true: ", valuea === valueb);
to achieve what you want, you either have to have added the actual reference, as I did above, or loop through the array and compare by unique property of the objects.
you can use find to returns the value of the this element
const array = [{a: 'b'}];
array.includes(array.find(el=>el.a==='b'));
const arr = [{a: 'b',b:'c'},{a: 'c'}]
console.log(arr.some(item => item.b === 'c'))
Yes, you can, if only so
const arr = [{a:'a'},{a: 'b'}]
const serch = arr[1]
console.log(arr.includes(serch))
You cannot use string comparisons on objects unless you first convert them to strings with...
JSON.stringify(TheObject)
So to loop through all objects in an array so as to prevent adding a duplicate object, you can use something like this...
let Bad=false;
ObjectArray.forEach(function(e){if(JSON.stringify(NewObject)===JSON.stringify(e)){Bad=true;}});
if(Bad){alert('This object already exists!');} else {ObjectArray.push(NewObject);}

Iterating through a list of mongoose documents returns 0 [duplicate]

I've been told not to use for...in with arrays in JavaScript. Why not?
The reason is that one construct:
var a = []; // Create a new empty array.
a[5] = 5; // Perfectly legal JavaScript that resizes the array.
for (var i = 0; i < a.length; i++) {
// Iterate over numeric indexes from 0 to 5, as everyone expects.
console.log(a[i]);
}
/* Will display:
undefined
undefined
undefined
undefined
undefined
5
*/
can sometimes be totally different from the other:
var a = [];
a[5] = 5;
for (var x in a) {
// Shows only the explicitly set index of "5", and ignores 0-4
console.log(x);
}
/* Will display:
5
*/
Also consider that JavaScript libraries might do things like this, which will affect any array you create:
// Somewhere deep in your JavaScript library...
Array.prototype.foo = 1;
// Now you have no idea what the below code will do.
var a = [1, 2, 3, 4, 5];
for (var x in a){
// Now foo is a part of EVERY array and
// will show up here as a value of 'x'.
console.log(x);
}
/* Will display:
0
1
2
3
4
foo
*/
The for-in statement by itself is not a "bad practice", however it can be mis-used, for example, to iterate over arrays or array-like objects.
The purpose of the for-in statement is to enumerate over object properties. This statement will go up in the prototype chain, also enumerating over inherited properties, a thing that sometimes is not desired.
Also, the order of iteration is not guaranteed by the spec., meaning that if you want to "iterate" an array object, with this statement you cannot be sure that the properties (array indexes) will be visited in the numeric order.
For example, in JScript (IE <= 8), the order of enumeration even on Array objects is defined as the properties were created:
var array = [];
array[2] = 'c';
array[1] = 'b';
array[0] = 'a';
for (var p in array) {
//... p will be "2", "1" and "0" on IE
}
Also, speaking about inherited properties, if you, for example, extend the Array.prototype object (like some libraries as MooTools do), that properties will be also enumerated:
Array.prototype.last = function () { return this[this.length-1]; };
for (var p in []) { // an empty array
// last will be enumerated
}
As I said before to iterate over arrays or array-like objects, the best thing is to use a sequential loop, such as a plain-old for/while loop.
When you want to enumerate only the own properties of an object (the ones that aren't inherited), you can use the hasOwnProperty method:
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// prop is not inherited
}
}
And some people even recommend calling the method directly from Object.prototype to avoid having problems if somebody adds a property named hasOwnProperty to our object:
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
// prop is not inherited
}
}
There are three reasons why you shouldn't use for..in to iterate over array elements:
for..in will loop over all own and inherited properties of the array object which aren't DontEnum; that means if someone adds properties to the specific array object (there are valid reasons for this - I've done so myself) or changed Array.prototype (which is considered bad practice in code which is supposed to work well with other scripts), these properties will be iterated over as well; inherited properties can be excluded by checking hasOwnProperty(), but that won't help you with properties set in the array object itself
for..in isn't guaranteed to preserve element ordering
it's slow because you have to walk all properties of the array object and its whole prototype chain and will still only get the property's name, ie to get the value, an additional lookup will be required
Because for...in enumerates through the object that holds the array, not the array itself. If I add a function to the arrays prototype chain, that will also be included. I.e.
Array.prototype.myOwnFunction = function() { alert(this); }
a = new Array();
a[0] = 'foo';
a[1] = 'bar';
for(x in a){
document.write(x + ' = ' + a[x]);
}
This will write:
0 = foo
1 = bar
myOwnFunction = function() { alert(this); }
And since you can never be sure that nothing will be added to the prototype chain just use a for loop to enumerate the array:
for(i=0,x=a.length;i<x;i++){
document.write(i + ' = ' + a[i]);
}
This will write:
0 = foo
1 = bar
As of 2016 (ES6) we may use for…of for array iteration, as John Slegers already noticed.
I would just like to add this simple demonstration code, to make things clearer:
Array.prototype.foo = 1;
var arr = [];
arr[5] = "xyz";
console.log("for...of:");
var count = 0;
for (var item of arr) {
console.log(count + ":", item);
count++;
}
console.log("for...in:");
count = 0;
for (var item in arr) {
console.log(count + ":", item);
count++;
}
The console shows:
for...of:
0: undefined
1: undefined
2: undefined
3: undefined
4: undefined
5: xyz
for...in:
0: 5
1: foo
In other words:
for...of counts from 0 to 5, and also ignores Array.prototype.foo. It shows array values.
for...in lists only the 5, ignoring undefined array indexes, but adding foo. It shows array property names.
Short answer: It's just not worth it.
Longer answer: It's just not worth it, even if sequential element order and optimal performance aren't required.
Long answer: It's just not worth it...
Using for (var property in array) will cause array to be iterated over as an object, traversing the object prototype chain and ultimately performing slower than an index-based for loop.
for (... in ...) is not guaranteed to return the object properties in sequential order, as one might expect.
Using hasOwnProperty() and !isNaN() checks to filter the object properties is an additional overhead causing it to perform even slower and negates the key reason for using it in the first place, i.e. because of the more concise format.
For these reasons an acceptable trade-off between performance and convenience doesn't even exist. There's really no benefit unless the intent is to handle the array as an object and perform operations on the object properties of the array.
In isolation, there is nothing wrong with using for-in on arrays. For-in iterates over the property names of an object, and in the case of an "out-of-the-box" array, the properties corresponds to the array indexes. (The built-in propertes like length, toString and so on are not included in the iteration.)
However, if your code (or the framework you are using) add custom properties to arrays or to the array prototype, then these properties will be included in the iteration, which is probably not what you want.
Some JS frameworks, like Prototype modifies the Array prototype. Other frameworks like JQuery doesn't, so with JQuery you can safely use for-in.
If you are in doubt, you probably shouldn't use for-in.
An alternative way of iterating through an array is using a for-loop:
for (var ix=0;ix<arr.length;ix++) alert(ix);
However, this have a different issue. The issue is that a JavaScript array can have "holes". If you define arr as:
var arr = ["hello"];
arr[100] = "goodbye";
Then the array have two items, but a length of 101. Using for-in will yield two indexes, while the for-loop will yield 101 indexes, where the 99 has a value of undefined.
In addition to the reasons given in other answers, you may not want to use the "for...in" structure if you need to do math with the counter variable because the loop iterates through the names of the object's properties and so the variable is a string.
For example,
for (var i=0; i<a.length; i++) {
document.write(i + ', ' + typeof i + ', ' + i+1);
}
will write
0, number, 1
1, number, 2
...
whereas,
for (var ii in a) {
document.write(i + ', ' + typeof i + ', ' + i+1);
}
will write
0, string, 01
1, string, 11
...
Of course, this can easily be overcome by including
ii = parseInt(ii);
in the loop, but the first structure is more direct.
Aside from the fact that for...in loops over all enumerable properties (which is not the same as "all array elements"!), see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, section 12.6.4 (5th edition) or 13.7.5.15 (7th edition):
The mechanics and order of enumerating the properties ... is not specified...
(Emphasis mine.)
That means if a browser wanted to, it could go through the properties in the order in which they were inserted. Or in numerical order. Or in lexical order (where "30" comes before "4"! Keep in mind all object keys -- and thus, all array indexes -- are actually strings, so that makes total sense). It could go through them by bucket, if it implemented objects as hash tables. Or take any of that and add "backwards". A browser could even iterate randomly and be ECMA-262 compliant, as long as it visited each property exactly once.
In practice, most browsers currently like to iterate in roughly the same order. But there's nothing saying they have to. That's implementation specific, and could change at any time if another way was found to be far more efficient.
Either way, for...in carries with it no connotation of order. If you care about order, be explicit about it and use a regular for loop with an index.
Mainly two reasons:
One
Like others have said, You might get keys which aren't in your array or that are inherited from the prototype. So if, let's say, a library adds a property to the Array or Object prototypes:
Array.prototype.someProperty = true
You'll get it as part of every array:
for(var item in [1,2,3]){
console.log(item) // will log 1,2,3 but also "someProperty"
}
you could solve this with the hasOwnProperty method:
var ary = [1,2,3];
for(var item in ary){
if(ary.hasOwnProperty(item)){
console.log(item) // will log only 1,2,3
}
}
but this is true for iterating over any object with a for-in loop.
Two
Usually the order of the items in an array is important, but the for-in loop won't necessarily iterate in the right order, that's because it treats the array as an object, which is the way it is implemented in JS, and not as an array.
This seems like a small thing, but it can really screw up applications and is hard to debug.
I don't think I have much to add to eg. Triptych's answer or CMS's answer on why using for...in should be avoided in some cases.
I do, however, would like to add that in modern browsers there is an alternative to for...in that can be used in those cases where for...in can't be used. That alternative is for...of :
for (var item of items) {
console.log(item);
}
Note :
Unfortunately, no version of Internet Explorer supports for...of (Edge 12+ does), so you'll have to wait a bit longer until you can use it in your client side production code. However, it should be safe to use in your server side JS code (if you use Node.js).
Because it enumerates through object fields, not indexes. You can get value with index "length" and I doubt you want this.
The problem with for ... in ... — and this only becomes a problem when a programmer doesn't really understand the language; it's not really a bug or anything — is that it iterates over all members of an object (well, all enumerable members, but that's a detail for now). When you want to iterate over just the indexed properties of an array, the only guaranteed way to keep things semantically consistent is to use an integer index (that is, a for (var i = 0; i < array.length; ++i) style loop).
Any object can have arbitrary properties associated with it. There would be nothing terrible about loading additional properties onto an array instance, in particular. Code that wants to see only indexed array-like properties therefore must stick to an integer index. Code that is fully aware of what for ... in does and really need to see all properties, well then that's ok too.
TL&DR: Using the for in loop in arrays is not evil, in fact quite the opposite.
I think the for in loop is a gem of JS if used correctly in arrays. You are expected to have full control over your software and know what you are doing. Let's see the mentioned drawbacks and disprove them one by one.
It loops through inherited properties as well: First of all any extensions to the Array.prototype should have been done by using Object.defineProperty() and their enumerable descriptor should be set to false. Any library not doing so should not be used at all.
Properties those you add to the inheritance chain later get counted: When doing array sub-classing by Object.setPrototypeOf or by Class extend. You should again use Object.defineProperty() which by default sets the writable, enumerable and configurable property descriptors to false. Lets see an array sub-classing example here...
function Stack(...a){
var stack = new Array(...a);
Object.setPrototypeOf(stack, Stack.prototype);
return stack;
}
Stack.prototype = Object.create(Array.prototype); // now stack has full access to array methods.
Object.defineProperty(Stack.prototype,"constructor",{value:Stack}); // now Stack is a proper constructor
Object.defineProperty(Stack.prototype,"peak",{value: function(){ // add Stack "only" methods to the Stack.prototype.
return this[this.length-1];
}
});
var s = new Stack(1,2,3,4,1);
console.log(s.peak());
s[s.length] = 7;
console.log("length:",s.length);
s.push(42);
console.log(JSON.stringify(s));
console.log("length:",s.length);
for(var i in s) console.log(s[i]);
So you see.. for in loop is now safe since you cared about your code.
The for in loop is slow: Hell no. It's by far the fastest method of iteration if you are looping over sparse arrays which are needed time to time. This is one of the most important performance tricks that one should know. Let's see an example. We will loop over a sparse array.
var a = [];
a[0] = "zero";
a[10000000] = "ten million";
console.time("for loop on array a:");
for(var i=0; i < a.length; i++) a[i] && console.log(a[i]);
console.timeEnd("for loop on array a:");
console.time("for in loop on array a:");
for(var i in a) a[i] && console.log(a[i]);
console.timeEnd("for in loop on array a:");
Also, due to semantics, the way for, in treats arrays (i.e. the same as any other JavaScript object) is not aligned with other popular languages.
// C#
char[] a = new char[] {'A', 'B', 'C'};
foreach (char x in a) System.Console.Write(x); //Output: "ABC"
// Java
char[] a = {'A', 'B', 'C'};
for (char x : a) System.out.print(x); //Output: "ABC"
// PHP
$a = array('A', 'B', 'C');
foreach ($a as $x) echo $x; //Output: "ABC"
// JavaScript
var a = ['A', 'B', 'C'];
for (var x in a) document.write(x); //Output: "012"
Here are the reasons why this is (usually) a bad practice:
for...in loops iterate over all their own enumerable properties and the enumerable properties of their prototype(s). Usually in an array iteration we only want to iterate over the array itself. And even though you yourself may not add anything to the array, your libraries or framework might add something.
Example:
Array.prototype.hithere = 'hithere';
var array = [1, 2, 3];
for (let el in array){
// the hithere property will also be iterated over
console.log(el);
}
for...in loops do not guarantee a specific iteration order. Although is order is usually seen in most modern browsers these days, there is still no 100% guarantee.
for...in loops ignore undefined array elements, i.e. array elements which not have been assigned yet.
Example::
const arr = [];
arr[3] = 'foo'; // resize the array to 4
arr[4] = undefined; // add another element with value undefined to it
// iterate over the array, a for loop does show the undefined elements
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
console.log('\n');
// for in does ignore the undefined elements
for (let el in arr) {
console.log(arr[el]);
}
In addition to the other problems, the "for..in" syntax is probably slower, because the index is a string, not an integer.
var a = ["a"]
for (var i in a)
alert(typeof i) // 'string'
for (var i = 0; i < a.length; i++)
alert(typeof i) // 'number'
An important aspect is that for...in only iterates over properties contained in an object which have their enumerable property attribute set to true. So if one attempts to iterate over an object using for...in then arbitrary properties may be missed if their enumerable property attribute is false. It is quite possible to alter the enumerable property attribute for normal Array objects so that certain elements are not enumerated. Though in general the property attributes tend to apply to function properties within an object.
One can check the value of a properties' enumerable property attribute by:
myobject.propertyIsEnumerable('myproperty')
Or to obtain all four property attributes:
Object.getOwnPropertyDescriptor(myobject,'myproperty')
This is a feature available in ECMAScript 5 - in earlier versions it was not possible to alter the value of the enumerable property attribute (it was always set to true).
The for/in works with two types of variables: hashtables (associative arrays) and array (non-associative).
JavaScript will automatically determine the way its passes through the items. So if you know that your array is really non-associative you can use for (var i=0; i<=arrayLen; i++), and skip the auto-detection iteration.
But in my opinion, it's better to use for/in, the process required for that auto-detection is very small.
A real answer for this will depend on how the browser parsers/interpret the JavaScript code. It can change between browsers.
I can't think of other purposes to not using for/in;
//Non-associative
var arr = ['a', 'b', 'c'];
for (var i in arr)
alert(arr[i]);
//Associative
var arr = {
item1 : 'a',
item2 : 'b',
item3 : 'c'
};
for (var i in arr)
alert(arr[i]);
Because it will iterate over properties belonging to objects up the prototype chain if you're not careful.
You can use for.. in, just be sure to check each property with hasOwnProperty.
It's not necessarily bad (based on what you're doing), but in the case of arrays, if something has been added to Array.prototype, then you're going to get strange results. Where you'd expect this loop to run three times:
var arr = ['a','b','c'];
for (var key in arr) { ... }
If a function called helpfulUtilityMethod has been added to Array's prototype, then your loop would end up running four times: key would be 0, 1, 2, and helpfulUtilityMethod. If you were only expecting integers, oops.
You should use the for(var x in y) only on property lists, not on objects (as explained above).
Using the for...in loop for an array is not wrong, although I can guess why someone told you that:
1.) There is already a higher order function, or method, that has that purpose for an array, but has more functionality and leaner syntax, called 'forEach': Array.prototype.forEach(function(element, index, array) {} );
2.) Arrays always have a length, but for...in and forEach do not execute a function for any value that is 'undefined', only for the indexes that have a value defined. So if you only assign one value, these loops will only execute a function once, but since an array is enumerated, it will always have a length up to the highest index that has a defined value, but that length could go unnoticed when using these loops.
3.) The standard for loop will execute a function as many times as you define in the parameters, and since an array is numbered, it makes more sense to define how many times you want to execute a function. Unlike the other loops, the for loop can then execute a function for every index in the array, whether the value is defined or not.
In essence, you can use any loop, but you should remember exactly how they work. Understand the conditions upon which the different loops reiterate, their separate functionalities, and realize they will be more or less appropriate for differing scenarios.
Also, it may be considered a better practice to use the forEach method than the for...in loop in general, because it is easier to write and has more functionality, so you may want to get in the habit of only using this method and standard for, but your call.
See below that the first two loops only execute the console.log statements once, while the standard for loop executes the function as many times as specified, in this case, array.length = 6.
var arr = [];
arr[5] = 'F';
for (var index in arr) {
console.log(index);
console.log(arr[index]);
console.log(arr)
}
// 5
// 'F'
// => (6) [undefined x 5, 6]
arr.forEach(function(element, index, arr) {
console.log(index);
console.log(element);
console.log(arr);
});
// 5
// 'F'
// => Array (6) [undefined x 5, 6]
for (var index = 0; index < arr.length; index++) {
console.log(index);
console.log(arr[index]);
console.log(arr);
};
// 0
// undefined
// => Array (6) [undefined x 5, 6]
// 1
// undefined
// => Array (6) [undefined x 5, 6]
// 2
// undefined
// => Array (6) [undefined x 5, 6]
// 3
// undefined
// => Array (6) [undefined x 5, 6]
// 4
// undefined
// => Array (6) [undefined x 5, 6]
// 5
// 'F'
// => Array (6) [undefined x 5, 6]
A for...in loop always enumerates the keys.
Objects properties keys are always String, even the indexed properties of an array :
var myArray = ['a', 'b', 'c', 'd'];
var total = 0
for (elem in myArray) {
total += elem
}
console.log(total); // 00123
for...in is useful when working on an object in JavaScript, but not for an Array, but still we can not say it's a wrong way, but it's not recommended, look at this example below using for...in loop:
let txt = "";
const person = {fname:"Alireza", lname:"Dezfoolian", age:35};
for (const x in person) {
txt += person[x] + " ";
}
console.log(txt); //Alireza Dezfoolian 35
OK, let's do it with Array now:
let txt = "";
const person = ["Alireza", "Dezfoolian", 35];
for (const x in person) {
txt += person[x] + " ";
}
console.log(txt); //Alireza Dezfoolian 35
As you see the result the same...
But let's try something, let's prototype something to Array...
Array.prototype.someoneelse = "someoneelse";
Now we create a new Array();
let txt = "";
const arr = new Array();
arr[0] = 'Alireza';
arr[1] = 'Dezfoolian';
arr[2] = 35;
for(x in arr) {
txt += arr[x] + " ";
}
console.log(txt); //Alireza Dezfoolian 35 someoneelse
You see the someoneelse!!!... We actually looping through new Array object in this case!
So that's one of the reasons why we need to use for..in carefully, but it's not always the case...
Since JavaScript elements are saved as standard object properties, it
is not advisable to iterate through JavaScript arrays using for...in
loops because normal elements and all enumerable properties will be
listed.
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections
although not specifically addressed by this question, I would add that there's a very good reason not to ever use for...in with a NodeList (as one would obtain from a querySelectorAll call, as it doesn't see the returned elements at all, instead iterating only over the NodeList properties.
in the case of a single result, I got:
var nodes = document.querySelectorAll(selector);
nodes
▶ NodeList [a._19eb]
for (node in nodes) {console.log(node)};
VM505:1 0
VM505:1 length
VM505:1 item
VM505:1 entries
VM505:1 forEach
VM505:1 keys
VM505:1 values
which explained why my for (node in nodes) node.href = newLink; was failing.
for in loop converts the indices to string when traversing through an array.
For example, In the below code, in the second loop where initialising j with i+1, i is the index but in a string ("0", "1" etc) and number + string in js is a string. if js encounters "0" + 1 it will return "01".
var maxProfit = function(prices) {
let maxProfit = 0;
for (let i in prices) {
for (let j = i + 1; j < prices.length; j++) {
console.log(prices[j] - prices[i], "i,j", i, j, typeof i, typeof j);
if ((prices[j] - prices[i]) > maxProfit) maxProfit = (prices[j] - prices[i]);
}
}
return maxProfit;
};
maxProfit([7, 1, 5, 3, 6, 4]);

What is the difference between elementsEqual and '==' in Swift?

I'm going through the Swift Standard Library, and I came across the method elementsEqual for comparing sequences.
I'm not really seeing the value of this function because it will only return true if the order is exactly the same. I figured this would have some use if it could tell me if two sequences contained the same elements, they just happen to be in a different order, as that would save me the trouble of sorting both myself.
Which brings me to my question:
Is there any difference between using elementsEqual and '==' when comparing two sequences? Are there pros and cons for one vs the other?
I am in my playground, and have written the following test:
let values = [1,2,3,4,5,6,7,8,9,10]
let otherValues = [1,2,3,4,5,6,7,8,9,10]
values == otherValues
values.elementsEqual(otherValues)
both of these checks result in true, so I am not able to discern a difference here.
After playing with this for a while to find a practical example for the below original answer I found a much more simple difference: With elementsEqual you can compare collections of different types such as Array, RandomAccessSlice and Set, while with == you can't do that:
let array = [1, 2, 3]
let slice = 1...3
let set: Set<Int> = [1, 2, 3] // remember that Sets are not ordered
array.elementsEqual(slice) // true
array.elementsEqual(set) // false
array == slice // ERROR
array == set // ERROR
As to what exactly is different, #Hamish provided links to the implementation in the comments below, which I will share for better visibility:
elementsEqual
==
My original answer:
Here's a sample playground for you, that illustrates that there is a difference:
import Foundation
struct TestObject: Equatable {
let id: Int
static func ==(lhs: TestObject, rhs: TestObject) -> Bool {
return false
}
}
// TestObjects are never equal - even with the same ID
let test1 = TestObject(id: 1)
let test2 = TestObject(id: 1)
test1 == test2 // returns false
var testArray = [test1, test2]
var copiedTestArray = testArray
testArray == copiedTestArray // returns true
testArray.elementsEqual(copiedTestArray) // returns false
Maybe someone knows for sure, but my guess is that == computes something like memoryLocationIsEqual || elementsEqual (which stops evaluating after the memory location is indeed equal) and elementsEqual skips the memory location part, which makes == faster, but elementsEqual more reliable.

Resources