0

I have an array:

var maxSpeed = {car:300, bike:60, motorbike:200, airplane:1000, helicopter:400, rocket:8*60*60}

I want to sort it and convert to FLAT object that will look exactly the same as the array above. Unfortunately after sorting and creating object I get multi-dimensional object:

var sortable = [];
for (var vehicle in maxSpeed)
      sortable.push([vehicle, maxSpeed[vehicle]])
sortable.sort(function(a, b) {return a[1] - b[1]});


function toObject(sortable) {
  var rv = {};
  for (var i = 0; i < sortable.length; ++i)
    rv[i] = sortable[i];
  return rv;
}

Check console.logs, one is nested the other one is not. I think I have to modify rv[i] = sortable[i] line, but I'm not sure how?

That's what I get now:

Object
0: Array[2]
1: Array[2]
2: Array[2]
3: Array[2]
4: Array[2]
5: Array[2]
__proto__: Object

And what I want to get:

Object
airplane: 1000
bike: 60
car: 300
helicopter: 400
motorbike: 200
rocket: 28800
__proto__: Object

JSFiddle:

http://jsfiddle.net/Tj39A/

Wordpressor
  • 7,173
  • 23
  • 69
  • 108
  • 3
    Sorry, `maxSpeed` is not an _Array_ but an _Object_ – Paul S. May 13 '14 at 13:10
  • 2
    Objects internally use hash algorithms to store the keys. So, we cannot explicitly order them. – thefourtheye May 13 '14 at 13:11
  • @PaulS. that's a common mistake of `PHP` devs when it comes to `JavaScript` – baldrs May 13 '14 at 13:12
  • Sorry, my bad, I meant object not array of course :) @Bergi, even if that's duplicate I'm using top-rated answer from original question and it doesn't seem to work as expected (it modifies the original array and makes it multi-dimensional). – Wordpressor May 13 '14 at 13:15
  • Try storing you data like this: `var maxSpeed = [{ vehicle : 'car', speed : 300 }, ...];`. You have objects in an array and you can sort those. – christian314159 May 13 '14 at 13:15
  • christian314159, nice one, although it creates Object within Object, still not perfectly flat as in original. I just want to sort an object without changing its structure, at all, and all snippets around here seem to do both :( – Wordpressor May 13 '14 at 13:17
  • Yes, of course it does create an array of key-value-tuples, because you don't want an object (which has no order!). – Bergi May 13 '14 at 13:30

1 Answers1

0

What you are looking for is something like this:

rv[sortable[i][0]] = sortable[i][1];

however as it has been pointed out an object cant be sorted the way you want.

George
  • 4,323
  • 3
  • 30
  • 33