1

If I have a dictionary of arrays, for example:

samples = {
   "labels": ["A", "B", "C"],
   "values": [2, 3, 1]
}

How do I sort the lists by the value order? For example, the output would be:

samples = {
   "labels": ["C", "A", "B"],
   "values": [1, 2, 3]
}

Would I need to convert the dictionary of lists into a list of dictionaries, sort by the values, then convert back, or is there a more direct way?

2 Answers 2

3

You could take the indices and sort these and then get the mapped arrays by using the sorted indices.

var samples = { labels: ["A", "B", "C"], values: [2, 3, 1] },
    indices = [...samples.values.keys()];

indices.sort((a, b) => samples.values[a] - samples.values[b]);

samples.labels = indices.map(i => samples.labels[i]);
samples.values = indices.map(i => samples.values[i]);

console.log(samples);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

This worked for me. Thanks! I was also able to extend it to sorting additional lists in the dictionary by adding more maps.
0

We can do this all in place.

First we map a new array giving us [{label, value}]
Then we sort on the value Finally we use reduce to rebuild to our original object.

let samples = {
   "labels": ["A", "B", "C"],
   "values": [2, 3, 1]
}

samples = samples.labels
       .map((label, i) => ({ label, value: samples.values[i] }))
       .sort(({ value: a }, { value: b }) =>  a - b)
       .reduce((a, { value, label }) => {         
          a.labels.push(label);
          a.values.push(value);
          return a;
       }, { labels: [], values: []});

console.log(JSON.stringify(samples));

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.