-1

Really struggling to find a solution here. I have the following data:

var arr = [
   { Main: {type: "object", ...} }
   { Poller: {type: "object", ...} }
   { connection: {type: "array", ...} }
   { Profile1: {type: "array", ...} }
   { Sender: {type: "object", ...} }
   { Profile2: {type: "array", ...} }
];

My goal is to generate an array that lists the objects of type: array first. I tried various implementations of the sort() method but don't know how to account for each nested object having its' own key. Any help is appreciated

1 Answers1

1

Like this

var arr = [
   { Main:       {type: "object",}},
   { Poller:     {type: "object",}},
   { connection: {type: "array" ,}},
   { Profile1:   {type: "array" ,}},
   { Func1:      {type: "function",}},
   { func2:      {type: "function",}},
   { Sender:     {type: "object",}},
   { Profile2:   {type: "array" ,}}
];

arr.sort((a, b) => {
  if (Object.values(a)[0].type < Object.values(b)[0].type) return -1
  if (Object.values(a)[0].type === Object.values(b)[0].type) return 0
  if (Object.values(a)[0].type > Object.values(b)[0].type) return 1
})
console.log(arr)
mplungjan
  • 169,008
  • 28
  • 173
  • 236