2

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]
}
1
  • 1
    I think the answer posted is good, however I wanted to add the suggestion to consider using an object instead of array. If ordering is not always the same, an object may be better. i.e. status : { data: {"high": 3, "mid": 4} } Commented Jul 19, 2021 at 18:24

1 Answer 1

2

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],
//}

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.