omar
omar

Reputation: 193

Reorder an array of values in an object in Javascript

I have the following object that I am trying to sort so that the labels are "High, mid, low" all of the time. The order I get them are not always the same so I wanted to add another layer of ordering to ensure that I get "high, mid, low"

Before:

status:{
    label:['mid', 'high', 'low'],
    data:[4, 3, 1]
}

After:

status:{
    label:['high', 'mid', 'low'],
    data:[3, 4, 1]
}

Upvotes: 2

Views: 75

Answers (1)

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

The easiest way to sort those two arrays "linked" is by temporarily combining them into one array:

const status = {
  label: ['mid', 'high', 'low'],
  data: [4, 3, 1]
};

// Combine the two arrays into an array of pairs
const pairs = status.label.map((label, index) => [label, status.data[index]]);
console.log('pairsBefore', pairs); // [ ['mid', 4 ], ['high', 3 ], ['low', 1 ]]

// Used for sorting
const ORDER = ['high', 'mid', 'low'];

// Sort the pairs
pairs.sort((a, b) => {
  const [labelA, dataA] = a;
  const [labelB, dataB] = b;
  // Gives 0 for 'high', 1 for 'mid' and 2 for 'low'
  const indexA = ORDER.indexOf(labelA);
  const indexB = ORDER.indexOf(labelB);
  // Substract for A and B, see how Array.prototype.sort works
  return indexA - indexB;
});
console.log('pairsAfter', pairs); // [ ['high', 3 ], ['mid', 4 ], ['low', 1 ]]

// Split it back into two arrays
const statusSorted = {
  label: pairs.map(pair => pair[0]),
  data: pairs.map(pair => pair[1]),
};
console.log('statusSorted', statusSorted);
//{
//    label: ['high', 'mid', 'low'],
//    data: [3, 4, 1],
//}

Upvotes: 2

Related Questions