This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 5 years ago.
I have a condition set up in typescript which compares 2 variables:
this.CurrentSelection == this.PreviousSelection
Both variables are arrays and can be an empty array ([]). In my app, I have a condition where each of these variables is an empty array (Array(0) in CDT watch). When the comparison happens between these 2 empty arrays, the result is false. It seems like [] == []. Any idea about the underlying reason for this? Do I need an additional "or" clause to check for length==0 for this scenario?
You're comparing references. The result will only be true if both a and b reference the same array:
const a = [];
const b = [];
const c = a;
console.log(a === b);
console.log(a === c);
If you want to check if both arrays contain the same values, you could do something like this:
function arrayEquals(a, b) {
return a.length === b.length && a.every((v, i) => v === b[i]);
}
console.log(
arrayEquals([1,2,3], [1,2,3])
);
Related
This question already has answers here:
Why doesn't equality check work with arrays [duplicate]
(6 answers)
Closed 6 months ago.
const obj ={Rating:7.5 , Actor:[], Age:undefined}
want to remove Actor:[]
function clean(obj) {
for (var propName in obj) {
if (obj[propName] === undefined || obj[propName] == [] ) {
delete obj[propName];
}
}
return obj
}
this function is only removing undefined values
Two different javascript objects cannot be equal
to each other.
Below is a demo of that:
console.log([] === [])
console.log([] == [])
In your specific case you will have to check two things:
The value is an array.
The array is actually empty.
If both are true, then your expression should evaluate to true.
let arr = [];
let arr2 = [1];
if(Array.isArray(arr) && arr.length === 0){
console.log('isempty');
}
if(Array.isArray(arr2) && arr2.length === 0){
console.log('isempty');
}
This question already has answers here:
Checking if a key exists in a JavaScript object?
(31 answers)
Closed 4 years ago.
Trying to figure out what the easiest way to write a function keyExisits that checks and arbitrarily nested key to see if it exists in an object and is undefined, vs does not exisit.
assume this obj
var obj = {
a: {
b: 1,
c: {
d: 2,
e: undefined
}
}
}
In this object the key a.c.e exists and is undefined, the key a.c.f does not exist
so
keyExists(obj, 'a.c.e') === true
keyExists(obj, 'a.c.f') === false
using lodash/underscore is ok
** UPDATE **
Lodash has works exactly like this
You can try following
var obj = {a: {b: 1,c: {d: 2,e: undefined}}};
function keyExists(o, key) {
if(key.includes(".")) {
let [k, ...rest] = key.split(".");
return keyExists(o[k], rest.join("."));
} else if(o) {
return o.hasOwnProperty(key);
}
return false;
}
console.log(keyExists(obj, 'a.c.e') === true)
console.log(keyExists(obj, 'a.c.f') === false)
Note: The above code will not work if there are any dots in the key name or you are using [] notation.
This question already has answers here:
How does (A == B == C) comparison work in JavaScript?
(6 answers)
Closed 6 years ago.
I'm trying to shorten out the following code:
var a = 0, b = 0;
function() {
return a === 0 && b === 0; // returns 'true'
}
So, I thought something like the following would do:
var a = 0, b = 0;
function() {
return a === b === 0; // returns 'false'
}
Initially, I thought that such syntax would throw an error, but apparently it returns false. Why does a === b === 0 return false?
The expression a === b === 0 is interpreted as if it were written (a === b) === 0. The result is false because (a === b) gives true, and true is not === to 0.
One can imagine a programming language that would understand a chain of expressions connected by == or === or whatever, meaning that all values should be compared in one big "group equality" comparison. JavaScript is not such a language, however.
This is due to how operators are evaluated. In JavaScript, equality operators are evaluated left-to-right (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
This means that this:
a === b === 0
Becomes this after one step:
true === 0
Since the number zero is not equal to the boolean true, your expression returns false.
This question already has answers here:
Using Function.prototype.bind with an array of arguments?
(11 answers)
Closed 7 years ago.
The closest I've seen is this, but it doesn't really help me since I need to bind some parameters for later use with setInterval.
More specifically:
[in] var d = function(l, m) {
console.log(l);
console.log(m);
}
[in] d.apply(window, [1,2])
[out] 1
[out] 2
[out-return-value] undefined
[in] d.bind(window, [1,2])()
[out] [1, 2]
[out] undefined
[out-return-value] undefined
As can be seen, arrays are unpacked with .apply(), but not with .bind(). Is there any way to unpack the arguments with .bind()?
.bind is just another function. Call it with .apply if you want to call it with an array of arguments:
var bound = d.bind.apply(d, [window, 1, 2]);
// If the `this` value is known, but the arguments is an array, concat:
// var bound = d.bind.apply(d, [window].concat(args))
Try this.
Function.prototype.bindArray(ctx, array) {
if (array && array.length && array.pop && array.length > 0) {
var v = array.pop();
return this.bindArray(ctx, array).bind(ctx, v);
}
else return this;
};
It will iteratively bind every value in array.
Use it like:
var d = function(l, m) {
console.log(l);
console.log(m);
};
var c = d.bindArray(null, [1,2]);
c(); // 1 2
Also see below #felix's answer. That's even cool.
This question already has answers here:
Object comparison in JavaScript [duplicate]
(10 answers)
Closed 9 years ago.
Here is one of the questions in JavaScript online-test before job interview:
function F(){};
var a = new F();
var b = new F();
Q: How to make comparison a == b to be true? (e.g. console.log(a == b) // true)
I answered that it's impossible because a and b are two different instances of F and equal comparison in JS in case of non-primitives compares reference.
But some time ago I've read article "Fake operator overloading in JavaScript" by Axel Rauschmayer: http://www.2ality.com/2011/12/fake-operator-overloading.html — and I wonder if there is a hack to fake operator overload in comparison of objects?
It really depends on what they mean by "How to make comparison a == b to be true?"
If you're allowed to change the constructor, then you could make your constructor a singleton:
function F(){
if (!F.instance) {
F.instance = this;
} else {
return F.instance;
}
};
var a = new F();
var b = new F();
if (a === b) {
//they are the same
}
If they want you to keep everything as it is but have a comparision that contains a == b then you could write the following:
if ("" + a == b) {
}
If they want to know methods of determine whether the two objects are instances of the same constructor function, then you could compare the constructor property or the __proto__ property:
if (a.constructor === b.constructor) {
}
if (a.__proto__ === b.__proto__) {
}
If they want to know methods of dermine whether these two objects have the same properties, you can either compare their JSON string:
if (JSON.stringify(a) === JSON.stringify(b)) {
}
or you write a function that recursively compares all the properties in both objects (deep comparision).
And the most simple answer to the question "How to make comparison a == b to be true?":
var a = new F();
var b = new F();
b = a;
if (a === b) {
//surprise!!!
}
my best answer would be this since you can compare different functions:
console.log(a.constructor+"" === b.constructor+"");
as it returns the functions as strings and then compare them literally .
example test:
function f1(){}
function f2(){}
var a = new f1(),
b= new f2();
console.log(a.constructor+"" === b.constructor+"");
b = new f1();
console.log(a.constructor+"" === b.constructor+"");
DEMO
note: the === sign is not needed as the third would be for type comparison and both are strings at that point so using == would do exactly the same thing
EDIT: my actual answer to the question however would be: by removing new from the initialization