Janine White
Janine White

Reputation: 499

How to sort Javascript arrays in a dictionary

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?

Upvotes: 1

Views: 240

Answers (2)

Bibberty
Bibberty

Reputation: 4768

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));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

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; }

Upvotes: 3

Related Questions