-2

I have 2 point objects as below, Please note that

  1. point1 (p1, p2, p3 and p4) are string type but they are decimal point numbers.

  2. point2 (p1, p2, p3 and p4) are numbers.

  3. There are other properties in the objects as well but I don't need to compare equality of them

  4. How can I compare equality for point1 (p1, p2, p3 and p4) === point2 (p1, p2, p3 and p4) only

    const point1 = {
      id: 1234,
      p1: "1.000000",
      p2: undefined,
      p3: "1.0",
      p4: "1.0",
      p5: "somevale 1"
    };
    
    const point2 = {
      id: 3456,
      p1: 1,
      p2: undefined,
      p3: 1,
      p4: 1,
      p5: "somevalue 2"
    };
    
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Chamie
  • 15
  • 1
  • 5

3 Answers3

1

Define an array of keys that you want to check the equality for, then use .every() on that array to iterate over each key. For each key, you can check if its value from point1 is numeric using isNaN(), and if it is, convert it to a number using the unary plus operator (+), otherwise, you can leave it as it's original value and compare this against the value at the key stored in point2. The callback to .every() needs to return true for all keys in your array for pointsEqual to be true, otherwise it will be false if there is a mismatch between two keys:

const point1 = { id: 1234, p1: "1.000000", p2: undefined, p3: "1.0", p4: "1.0", p5: "somevale 1" };
const point2 = { id: 3456, p1: 1, p2: undefined, p3: 1, p4: 1, p5: "somevalue 2" };

const keys = ["p1", "p2", "p3", "p4"];
const pointsEqual = keys.every(
  key => (isNaN(point1[key]) ? point1[key] : +point1[key]) === point2[key]
);
console.log(pointsEqual); // true
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

If you are using Javascript, you need to loop through items and compare individually. Also, === is for type check. Use == to skip type check.

Manny
  • 679
  • 5
  • 12
0

You can use a for loop to loop from 1 to 4 and get the corresponding property by concatenating "p" to the index like so:

const point1 = {
  id: 1234,
  p1: "1.000000",
  p2: undefined,
  p3: "1.0",
  p4: "1.0",
  p5: "somevale 1"
};
const point2 = {
  id: 3456,
  p1: 1,
  p2: undefined,
  p3: 1,
  p4: 1,
  p5: "somevalue 2"
};
var isEqual = true;
for(let i = 1; i < 5; i++){
  if(point1["p"+i] !== point2["p"+i]){
    isEqual = false;
  }
}
console.log(isEqual);

Note the difference between != and !==. (one compares types, the other does not)

Spectric
  • 30,714
  • 6
  • 20
  • 43
  • p1, p2, p3 p4 are just for filed name to explain the question here but actually they have unique names which doesn't have a pattern – Chamie Jul 12 '21 at 03:27