0

I have this data:

enter image description here

There are three columns r_code, wtg_code and rr. Every row can be treated as a collection of object properties. We have to select n number of rows from the existing rows. Considering the row are sorted in decreasing order of r_code, constraints are,

  1. Select the rows in decreasing order of r_code, many rows can have the same r_code.
  2. If many rows have the same r_code, then select on the basis of decreasing wtg_code.
  3. If multiple rows have the same wtg_code then select on the basis of lowest rr.

If you can give the solution in Javascript then it will be better otherwise I welcome any language.

trincot
  • 317,000
  • 35
  • 244
  • 286
PS95
  • 125
  • 1
  • 1
  • 7
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Feb 10 '22 at 12:28
  • Thank you @SebastianSimon. – PS95 Feb 10 '22 at 15:40

1 Answers1

0

In JavaScript, the data can be represented like this:

let data = [
    { r_code: 5, wtg_code: 8, rr: 3.4 },
    { r_code: 5, wtg_code: 8, rr: 3.4 },
    { r_code: 5, wtg_code: 7, rr: 4.5 },
    { r_code: 4, wtg_code: 6, rr: 1.2 },
    { r_code: 4, wtg_code: 6, rr: 2.4 },
    { r_code: 4, wtg_code: 6, rr: 4.5 },
    { r_code: 2, wtg_code: 6, rr: 1.6 },
    { r_code: 2, wtg_code: 5, rr: 7.4 },
    { r_code: 1, wtg_code: 4, rr: 3.1 },
    { r_code: 1, wtg_code: 4, rr: 2.9 },
    { r_code: 1, wtg_code: 3, rr: 3.3 },
];

Considering the row are sorted in decreasing order of r_code

That could still allow for several permutations. The rules for selection really mean that you should sort the data more precisely: by descending r_code, descending wtg_code and ascending wtg_code.

For that you can use the sort method.

data.sort((a, b) => b.r_code - a.r_code || b.wtg_code - a.wtg_code || a.rr - b.rr);

Finally, if you are interested in the first 10 (n=10), then slice:

let n = 10;
console.log(data.slice(0, n));
trincot
  • 317,000
  • 35
  • 244
  • 286