Array.prototype.sort() for object pairs

I get a function's results in an array of objects:

let options = [
  {
    "aCol": 0,
    "aRow": 10,
    "bCol": 12,
    "bRow": 4,
    "cCol": 5,
    "cRow": 1,
  },
  {
    "aCol": 4,
    "aRow": 10,
    "bCol": 3,
    "bRow": 4,
    "cCol": 1,
    "cRow": 1,
  },
  {
    "aCol": 4,
    "aRow": 10,
    "bCol": 3,
    "bRow": 0,
    "cCol": 0,
    "cRow": 1,
  }
];

that I want to inspect the value pairs, i.e.:

aCol
aRow

and sort them in ascending order by the number of zeroes am amongst the three pairs. The result should be:

let options = [
  {
    "aCol": 4,
    "aRow": 10,
    "bCol": 3,
    "bRow": 0, // b contains a zero
    "cCol": 0, // c contains a zero
    "cRow": 1,
  },
  {
    "aCol": 0, // a contains a zero
    "aRow": 0,
    "bCol": 12,
    "bRow": 4,
    "cCol": 5,
    "cRow": 1,
  },
  {
    "aCol": 4,  // no zeroes in this object in any of the pairs
    "aRow": 10,
    "bCol": 3,
    "bRow": 4,
    "cCol": 1,
    "cRow": 1,
  },
];

I've been messing around leveraging the zeroes and with shortcutting like this:

options.sort((x,y) => 
  (x.aCol * x.aRow < y.aCol * y.aRow) ||
  (x.bCol * x.bRow < y.bCol * y.bRow) ||
  (x.cCol * x.cRow < y.cCol * y.cRow) 
) 

console.log(...options); 


Read more here: https://stackoverflow.com/questions/64397109/array-prototype-sort-for-object-pairs

Content Attribution

This content was originally published by Jim from Princeton at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: