You would need to extend the array of cars with an extra method.
Note however, that this is not really considered best practice, as users of your code would expect arrays to be plain arrays -- nothing more, nothing less.
Anyway:
class Garage {
constructor() {
this._cars = Object.assign([], { brands: () => this.carsBrands() });
}
addCar(brand, year) {
this._cars.push({brand, year});
return this;
}
get cars() {
return this._cars;
}
carsBrands() {
return [...new Set(this._cars.map(car => car.brand))]; // make unique
}
}
let garage = new Garage();
garage.addCar("Toyota", 2007).addCar("BMW", 2019);
console.log(garage.cars);
console.log(garage.cars.brands());
A more acceptable design could be to let cars
be a plain object with a few different methods, among which a method to get the array of objects, and one to get the array of brand names.
For example:
class Garage {
constructor() {
this.cars = {
entries: [],
get brands() {
return [...new Set(this.entries.map(car => car.brand))];
}
};
}
addCar(brand, year) {
this.cars.entries.push({brand, year});
return this;
}
}
let garage = new Garage();
garage.addCar("Toyota", 2007).addCar("BMW", 2019);
console.log(garage.cars.entries);
console.log(garage.cars.brands);