I have a code snippet that requires sorting each element in an array based on their area.
function Rectangle(base, height) {
this.base = base;
this.height = height;
this.area = function () {
return this.base * this.height;
};
this.perimeter = function () {
return 2 * (this.base + this.height);
};
this.toString = function () {
return (
'(b= ' +
this.base +
', h= ' +
this.height +
', a = ' +
this.area() +
', p =' +
this.perimeter() +
')'
);
};
}
var rectangles = [
new Rectangle(1, 1),
new Rectangle(2, 2.05),
new Rectangle(2, 5),
new Rectangle(1, 3),
new Rectangle(4, 4),
new Rectangle(2, 8)
];
To achieve this, I plan to first declare a method in the Array class of JavaScript and then sort it using the sort() method.
array.prototype.sortByArea = function() {
};
Can someone guide me on how to accomplish this task?