0

I have an array of objects like below:

    [{
    "id": 1,
    "Size": 90,
    "Maturity": 24,
   },
  {
    "id": 2,
    "Size": 85,
    "Maturity": 22,
  },
  {
    "id": 3,
    "Size": 80,
    "Maturity": 20,
   }]

I need to this Array on basis of different property value sorting (eg: Maturity) and also add a column order which has the ascending order/rank. Eg:

      [{
        "id": 1,
        "Size": 90,
        "Maturity": 22,
         "Order": 2
       },
      {
        "id": 2,
        "Size": 85,
        "Maturity": 25,
        "Order": 3
      },
      {
        "id": 3,
        "Size": 80,
        "Maturity": 20,
        "Order": 1
       }]
3
  • In which language will you do that? By the way, your sample order numbering is not accurate, am I wrong? Commented Mar 13, 2019 at 12:40
  • @vahdet Edited the question. I need it in AngularJS. Commented Mar 13, 2019 at 12:51
  • The two examples have different data so it is hard to understand what you are asking. Also, you should post your code, so we can see what you tried. Commented Mar 13, 2019 at 12:57

3 Answers 3

1
const arr = [{
    "id": 1,
    "Size": 90,
    "Maturity": 24,
   },
   {
    "id": 2,
    "Size": 85,
    "Maturity": 22,
   },
   {
    "id": 3,
    "Size": 80,
    "Maturity": 20,
   }];

arr
  .map((item,index) => ({ ...item, Order: index + 1 }))
  .sort((a, b) => b.Maturity - a.Maturity)
Sign up to request clarification or add additional context in comments.

Comments

0

Sort the array with sort and then add prop to each object with respect to the index they are sorted on with forEach:

var inp = [{
    id: 1,
    Size: 90,
    Maturity: 24,
   },
  {
    id: 2,
    Size: 85,
    Maturity: 22,
  },
  {
    id: 3,
    Size: 80,
    Maturity: 20,
   }]
   
// Sort
inp.sort(function(a, b){
  return a.Maturity == b.Maturity ? 0 : +(a.Maturity > b.Maturity) || -1;
});

// add prop
inp.forEach(function(row, index) {
  row.index = index + 1;
});

console.log(inp)

Comments

0
var objs = [ 
    {
    "id": 1,
    "Size": 90,
    "Maturity": 24,
   },
  {
    "id": 2,
    "Size": 85,
    "Maturity": 22,
  },
  {
    "id": 3,
    "Size": 80,
    "Maturity": 20,
   }];
function compare(a,b) {
  if (a.Size < b.Size)
    return -1;
  if (a.Size > b.Size)
    return 1;
  return 0;
}

objs.sort(compare);
for (var i = 0; i < objs.length; i++) {
    objs[i].Order = i+1;
}
console.log(objs);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.