2

I have this object:

var myObject = {
    cat: {
        order: 1
    },

    mouse: {
        order: 4
    },

    dog: {
        order: 2
    },   

    shark: {
        order: 3
    }
}

I'm trying to get back: ["cat", "dog", "shark", "mouse"]

I tried:

_.sortBy(x, function(e) { return e.order} )

Luca Kiebel
  • 9,200
  • 6
  • 29
  • 43
Batman
  • 4,882
  • 14
  • 70
  • 145

4 Answers4

7

You can simply use Object.keys() and Array.sort() for it.

  • get all the keys from the Object using Object.keys().
  • Simply sort all the keys by passing a custom Comparator to the sort function which compares the order property of the keys in the object.

var myObject = { cat: { order: 1 }, mouse: { order: 4 }, dog: { order: 2 }, shark: { order: 3 } };

let result = Object.keys(myObject).sort((a,b)=> myObject[a].order -  myObject[b].order);

console.log(result);
amrender singh
  • 7,430
  • 3
  • 20
  • 27
6

use Object.entries first, then sort by the order property of its second element (because Object.entries returns an array of a given object's own enumerable property [key, value] pairs), finally use Array.map to get what you need.

var myObject = {
  cat: {
    order: 1
  },
  mouse: {
    order: 4
  },
  dog: {
    order: 2
  },
  shark: {
    order: 3
  }
}

console.log(
  Object.entries(myObject).sort((a, b) => {
    return a[1].order - b[1].order
  }).map(item => item[0])
)
Sphinx
  • 10,163
  • 2
  • 24
  • 41
0

    var myObject = {
    cat: {
        order: 1
    },

    mouse: {
        order: 4
    },

    dog: {
        order: 2
    },   

    shark: {
        order: 3
    }
}     
let oKeys = Object.keys(myObject)

     let tempArray = []

     oKeys.forEach(function(key) {
        tempArray[myObject[key]['order']-1] = key
     })
          
   
     console.log(tempArray)
Steve Bohmbach
  • 317
  • 1
  • 10
  • Why use `.map` when you are not using it for mapping functionality? This should be a `.forEach`. Then again, the body of the callback seems to be wrong, too. – VLAZ Sep 12 '18 at 18:54
  • 1
    You should consider making a runnable snippet so you can identify the errors it throws. hint: you probably want something more like: `tempArray[myObject[key].order -1] = key` (and forEach as vlaz mentioned) – Mark Sep 12 '18 at 18:54
  • Thanks for the feedback @MarkMeyer – Steve Bohmbach Sep 12 '18 at 19:03
0

Here is a solution using lodash.

Use _.map and _.sort for it.

  • First, _.map to array of order and name.
  • Then, _.sort and _.map name

By using lodash chain, make the code easy to read.


 _(myObject)
   .map((v, k) => ({order: v.order, name: k}))
   .sortBy('order')
   .map('name')
   .value()
Ali Yang
  • 366
  • 2
  • 6