1

I have below code in node -

function ABC(a,b,c) {
 this.a = a;
 this.b = b;
 this.c = c;
 this.equals = function(other) {
 return other.a == this.a &&
 other.b == this.b &&
 other.c === this.c;
 };
}
var a1 = new ABC("1", "1", 0.94924088690462316);
var a2 = new ABC("1", "1", 0.94924088690462316);
console.log(a1 === a2);
var arr = [a1];
console.log(arr.includes(a2));

This code outputs is -

 false
 false

how can I check whether the array includes the specific object is true?

asked Jul 24, 2019 at 23:10
2
  • Are you expecting an output of true because their properties and values are all the same? Commented Jul 24, 2019 at 23:12
  • @Snow - yeah. That's correct Commented Jul 24, 2019 at 23:39

2 Answers 2

3

Since it look like you're trying to check whether the objects contain the same values, see that you've already defined an equals method - just use it:

function ABC(a,b,c) {
 this.a = a;
 this.b = b;
 this.c = c;
 this.equals = function(other) {
 return other.a == this.a &&
 other.b == this.b &&
 other.c === this.c;
 };
}
var a1 = new ABC("1", "1", 0.94924088690462316);
var a2 = new ABC("1", "1", 0.94924088690462316);
console.log(a1.equals(a2));

You can make the code more efficient by defining the method on the prototype:

function ABC(a, b, c) {
 this.a = a;
 this.b = b;
 this.c = c;
}
ABC.prototype.equals = function(other) {
 return other.a == this.a &&
 other.b == this.b &&
 other.c === this.c;
};
var a1 = new ABC("1", "1", 0.94924088690462316);
var a2 = new ABC("1", "1", 0.94924088690462316);
console.log(a1.equals(a2));

Also, keep in mind that 0.94924088690462316 holds too many significant figures for Javascript to handle - that number will be stored as 0.9492408869046232:

console.log(0.94924088690462316);

answered Jul 24, 2019 at 23:13
2

Only slightly different from Snow's answer:

function ABC(a,b,c) {
 this.a = a;
 this.b = b;
 this.c = c;
 this.equals = function(other) {
 return other.a == this.a &&
 other.b == this.b &&
 other.c === this.c;
 };
}
var a1 = new ABC("1", "1", 0.94924088690462316);
var a2 = new ABC("1", "1", 0.94924088690462316);
console.log(a1.equals(a2));
var arr = [a1];
console.log(arr.some(abc => (a1.equals(abc))));

answered Jul 24, 2019 at 23:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.