1
var data = {
 chart : 'rank',
 labels: [
      {
       0: 'First Choice'
       1: 'Second Choice',   
       2: 'Third Choice',
       3: 'Fourth Choice',
       4: 'Fifth Choice'
      }
 ],
rows: [
     {
      0: 2,
      1: 8,
      2: 1,
      3: 30
      4: 4
     }
      ]

   }

Is there a way to reorder the results so that the rows are reordered highest to lowest and the corresponding labels are reordered too like the below:

var data = {
 chart : 'rank',
 labels: [
      {
       0: 'Fourth Choice'
       1: 'Second Choice',   
       2: 'Fifth Choice',
       3: 'First Choice',
       4: 'Third Choice'
      }
 ],
rows: [
     {
      0: 30,
      1: 8,
      2: 4,
      3: 2
      4: 1
     }
      ]

   }

So far I have managed to reorder the rows array using the following but stuck when it comes to labels?

rows = rows.sort(function(a, b){return b-a});
6
  • sort of method can't use with Object Commented Jul 26, 2016 at 7:49
  • @PranavCBalan I have used sort of for an array after parseJSON(data); Commented Jul 26, 2016 at 7:50
  • you are applying sort method on the single element array.... I think you need to rearrange the value in the array element object Commented Jul 26, 2016 at 7:51
  • Thanks @PranavCBalan, I've got that. Looking for examples or more direction of how to achieve that Commented Jul 26, 2016 at 7:54
  • @PranavCBalan Sorry but that sentence doesn't make much sense to me. Commented Jul 26, 2016 at 8:08

1 Answer 1

2

Get the object values into an array and sort it. After sorting update the real object based on sorted array.

var data = {
  chart: 'rank',
  labels: [{
    0: 'First Choice',
    1: 'Second Choice',
    2: 'Third Choice',
    3: 'Fourth Choice',
    4: 'Fifth Choice'
  }],
  rows: [{
    0: 2,
    1: 8,
    2: 1,
    3: 30,
    4: 4
  }]
};
// get object property name array
Object.keys(data.labels[0])
  // generate array with object values
  .map(function(k) {
    return [data.labels[0][k], data.rows[0][k]]
      // sort the array based on rows value in array
  }).sort(function(a, b) {
    return b[1] - a[1];
    // iterate and update real object
  }).forEach(function(v, i) {
    data.labels[0][i] = v[0];
    data.rows[0][i] = v[1];
  });

console.log(data);

Sign up to request clarification or add additional context in comments.

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.