Code Tips #9: Javascript – Compare objects

Many times we are in situations where we want to compare instances of a class, aka objects. Let’s see it with an example

class Car {
  constructor(speed){
    this.speed = speed
  }
}


const car1 = new Car(100)
const car2 = new Car(120)
const car3 = new Car(90)

console.log(car2.speed > car1.speed) // true

const sorted = [car1, car2, car3].sort((a,b) => {
  return a.speed - b.speed;
});

console.log(sorted) // [ Car { speed: 90 }, Car { speed: 100 }, Car { speed: 120 } ]

This works perfectly fine but we can do better

, we don’t have to type .speed every time we want to compare two cars, or sort/filter an array of them. We can define a valueOf method in the Car class, the method returns the “value” of the instance.

class Car {
  constructor(speed){
    this.speed = speed
  }

  valueOf(){
    return this.speed;
  }
}


const car1 = new Car(100)
const car2 = new Car(120)
const car3 = new Car(90)

console.log(car2 > car1) // true

console.log([car1, car2, car3].sort((a,b) => a - b)) // [ Car { speed: 90 }, Car { speed: 100 }, Car { speed: 120 } ]

Leave a Reply

Your email address will not be published. Required fields are marked *