Order array by Attribute in JavaScript

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?

Answer №1

To compare, simply subtract the areas.

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)
];
rectangles.sort((a, b) => a.area() - b.area());
rectangles.forEach(x => console.log(x.toString()));

If there is a strong need to modify the Array's prototype, it can be done but not recommended.

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)
];
Array.prototype.sortByArea = function(){
  return this.sort((a, b) => a.area() - b.area());
}
rectangles.sortByArea();
rectangles.forEach(x => console.log(x.toString()));

Answer №2

Here is the solution you are seeking:

Method to modify the original array:

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)
];
console.log('rectangles (before):');
rectangles.forEach(item => console.log(item.area()));

Array.prototype.sortByArea = function() {
  return this.sort(function(rectA, rectB) {
    return rectA.area() - rectB.area();
  });
}

rectangles.sortByArea();

console.log('rectangles (after):');
rectangles.forEach(item => console.log(item.area()));

Method to return an ordered copy of the original array:

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)
];
console.log('rectangles (before):');
rectangles.forEach(item => console.log(item.area()));

Array.prototype.sortByArea = function() {
  return this.map(item => item).sort(function(rectA, rectB) {
    return rectA.area() - rectB.area();
  });
}

const sortedRectangles = rectangles.sortByArea();


console.log('sortedRectangles:');
sortedRectangles.forEach(item => console.log(item.area()));
console.log('rectangles (after):');
rectangles.forEach(item => console.log(item.area()));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method for displaying over 1000 2D text labels using three.js?

Currently, I am in the process of designing a floor plan that includes over 1000 2D meshes with shapeGeometry and basicMeshMaterial on the scene. I also need to incorporate 2D text within these meshes while ensuring that the text is hidden within the bound ...

Is there a way to receive a string of variable length using getchar without prompting the user for the string size beforehand?

I am struggling to collect user input using only getchar() and malloc() to store it in a string of unknown size. Although I have done this successfully before, I seem to have forgotten the correct method. Currently, I am facing an issue where my function i ...

What is the process for uploading an image to Postman with Express.js?

I have a collection of jpeg and png images saved on my local machine. What is the process for displaying them in Postman using express.js? Should I utilize sendFile? Is it feasible to showcase multiple images at once? Below is a sample code snippet: app ...

"The issue persists with multiple JavaScript forms failing to work as expected when preventDefault

Within a jQuery document ready function, I've included the following code: jQuery("#frmUpdateDet").submit(function (e) { jQuery.ajax({ type: 'POST', url: './php/updateCred.php', data: jQ ...

Issues with CodeIgniter Calendar Preferences template functionality

Check out the $prefs. $prefs = array( 'month_type' => 'long', 'day_type' => 'short', 'show_next_prev' => true, 'next_prev_url' => ...

Discover past stock prices on Yahoo Finance

I'm stuck on tweaking a functioning jfiddle example that I have. Can anyone help me with this two-part question regarding the jfiddle: http://jsfiddle.net/maxmillien/qPVSy/ Part 1) Is there a way to clear the search each time a new search is performe ...

Guide on making a submit and close button within an overlay

Seeking a button to both submit and close an overlay window. The button code is as follows: <a href="javascript:additem('Info to add here', 10.00,1);" role="button"><button class="purchase btn btn-warning">Select</button></ ...

What is the best way to upgrade to a specific version of a child dependency within a module?

npm version: 7.24.2 Looking for assistance on updating a child dependency. The dependency in question is: vue-tel-input This dependency relies on libphonenumber-js with version ^1.9.6 I am aiming to update libphonenumber-js to version ^1.10.12. I have ...

Adding a characteristic to every item in an array of objects

Currently, I am utilizing Node.js along with Mongoose to interact with a MongoDB database and retrieve an array of objects from a specific collection. However, my aim is to add an additional property to each of these retrieved objects. Below, you can see t ...

Activate the CSS on a click event using the onClick method

I am trying to implement a transition that triggers when clicking on a specific div element. Currently, the transition only occurs with the active css class. How can I achieve this effect by simply clicking on the div itself? I am using reactjs and believe ...

Using a render target causes certain elements of my visual graphics to become hidden

Hey there, I've been experimenting with render targets lately and encountered some issues. I've put together a simplified example below: init = function() { // RENDERER canvas = document.getElementById("mycanvas"); renderer = new THREE ...

The Nestjs cronjob is having trouble accessing the injected service

After setting up a cronjob to call a service from another module, I encountered an issue where the console logged items were displaying correctly when running the method manually from the endpoint. However, once I added back the cronjob decorator, the serv ...

Performing an Ajax request using MooTools when my button is clicked

After clicking a button, I want to initiate an ajax call. There are more than 14 buttons on my site that make ajax requests to fetch elements from various parts of the site. Button, Button1, Button2, Button3 | | | load content | | ...

Tips for creating an angularjs login page as the initial page

I am new to working with AngularJS and I have been experimenting with the generator-angular-fullstack, My goal is to have the login page load first instead of the main page. After playing around with the code, I found a solution by adding 'authentica ...

Exploring Uncharted Territory: Defining Array Bounds and Iterating through

My current struggle lies within the boundaries of an array as I work with 3 different worksheets. In the first two sheets, I convert information into arrays (referred to as array1 and array2) and perform calculations between them to generate a third array. ...

What is the process for running a continuous stream listener in a node.js function?

I am currently working with a file called stream.ts: require('envkey') import Twitter from 'twitter-lite'; const mainFn = async () => { const client = new Twitter({ consumer_key: process.env['TWITTER_CONSUMER_KEY'], ...

Conceal all div elements except for displaying the initial two

Can an entire div be hidden with only the first 2 entities visible? <div class="inline-edit-col"> <span class="title inline-edit-categories-label">Brands</span> <ul class="cat-checklist product_brand-checklist"> < ...

Creating Low-Poly Terrain with a Touch of Serendipity

Looking to create terrain in a low-poly style inspired by the landscapes in Cube Slam and this video. I experimented with the webgl_geometry_terrain.html example, but it's still generating smooth terrain instead of the flat polygons I'm aiming fo ...

Spontaneous gradient background occasionally failing to load as expected

My to-do list is simple and functional, but I'm encountering an unusual issue with the background. The background is supposed to be a random gradient set using JS upon loading the HTML, but sometimes it doesn't apply at all. If you refresh the Co ...

The `user-select: none` property displays distinct behavior in Safari

My Goal I am in the process of creating an input-like content editable div. The idea is to click on tags outside the div and insert them inside the div while still being able to type around these tags. The Issue and Reproduction Steps To prevent tag but ...