-2

I currently have an object of objects, and I am looking to sort three of the objects of objects on one of the objects of objects values.

For example, if i have

{ A : { 1: 5, 2: 10,  3: 7}, 
  B : { 1: Alpha, 2: Beta, 3: Charlie}, 
  C : { 1: Z, 2: Y, 3: X} 
}

I want to sort the object in A by the value (in desc order), while keeping the integrity of the key. And this same sort is done for B and C (orderwise).

The resulting arrays would be [10, 7, 5], [Beta, Charlie, Alpha], and [Y, X, Z].

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Are all the values in `A` unique? – Barmar Dec 25 '19 at 00:02
  • 1
    Question is answered here: [Sort two arrays the same way](https://stackoverflow.com/questions/11499268/sort-two-arrays-the-same-way) – Andrew Dec 25 '19 at 00:02
  • Convert the `A` object into an array like `[[1, 5], [2, 10], [3, 7]]`. Sort it by the second element of each sub-array. Then create result arrays that are the elements of each original property in the order of the first element of each sub-array in that sorted array. – Barmar Dec 25 '19 at 00:05
  • @Barmar The values in A are unique. Thank you the methodology, I will look into it. – Daniel Chen Dec 31 '19 at 18:35

1 Answers1

0

Use Object.values(), Object.entries(), and.sort().

var obj = 
{ A : { 1: 5, 2: 10,  3: 7}, 
  B : { 1: "Alpha", 2: "Beta", 3: "Charlie"}, 
  C : { 1: "Z", 2: "Y", 3: "X"} 
};
obj = Object.values(obj);

var sorted = Object.entries(obj[0]).sort((a, b) => b[1] - a[1]);

var output = [];

sorted.forEach((v, i) => {
    output.push(obj.map(e => e[v[0]]));
})

console.log(output);

//new array with first of each array
var newarr = output.map(a => a[0]);

console.log(newarr);
Yousername
  • 1,012
  • 5
  • 15
  • Thank you. The next step would be to extract the 1st element of each array and store it into a new array. This is done for each nth element. – Daniel Chen Dec 31 '19 at 18:37
  • I am still running into an error where the defined obj is not an array, but rather an object. Therefore, the .sort method can't be ran. – Daniel Chen Jan 02 '20 at 22:07