javascript array of object add rank but don’t change order of the main array

I want to add a rank key on each element based on totalpremium value(but I don't want to change the order of objects inside array), My current code works fine but It changes the order of the main array of object which I don't want to do.

Array of objects:

 [
  {
    totalcount: 2834682,
    totalpremium: 652553820
  },
  {
    totalcount: 1380674,
    totalpremium: 430713235
  },
  {
    totalcount: 862119,
    totalpremium: 165983898
  }
]

Working Function

// add rank to each object
function rank_by_key(array, key_name) {

    if (key_name) {

        array.sort(function (a, b) {
            return b[key_name] - a[key_name];
        });

        var rank = 1;
        for (var i = 0; i < array.length; i++) {
            if (i > 0 && array[i][key_name] < array[i - 1][key_name]) {
                rank++;
            }
            array[i].rank = rank;
        }
    }
    return array;
}


ranked_result = rank_by_key(array, 'totalpremium');

Expected Output:

      [
        {
          "totalcount": 2834682,
          "totalpremium": 110,
          "rank": 2
        },
        {
          "totalcount": 1380674,
          "totalpremium": 121,
          "rank":1
        },
        {
          "totalcount": 862119,
          "totalpremium": 100,
          "rank": 3
        }
      ]
    

Current Output:

      [
        {
          "totalcount": 1380674,
          "totalpremium": 121,
          "rank":1
        },
        {
          "totalcount": 2834682,
          "totalpremium": 110,
          "rank": 2
        },
        {
          "totalcount": 862119,
          "totalpremium": 100,
          "rank": 3
        }
      ]
    


Read more here: https://stackoverflow.com/questions/68489113/javascript-array-of-object-add-rank-but-dont-change-order-of-the-main-array

Content Attribution

This content was originally published by Always Sunny 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: