1

I use javascript dictionary for a big list , and complete it like under code

var child = { 
     id:1,
     values:30
};

var array = [] ; 
array.push(child);

I want sorting this array by value field my problem is that I can't find a javascript method for it I can write it manually, but it is my last hope

Liath
  • 9,913
  • 9
  • 51
  • 81
Pnsadeghy
  • 1,279
  • 1
  • 13
  • 20
  • 3
    Try `array.sort(function(a,b){return a.values-b.values})` – elclanrs Feb 03 '14 at 08:20
  • 1
    possible duplicate of [Iterate over a Javascript associative array in sorted order](http://stackoverflow.com/questions/890807/iterate-over-a-javascript-associative-array-in-sorted-order) – Cerbrus Feb 03 '14 at 08:22
  • Please google your problem before asking about it on SO. Sorting dicts has been done numerous times before, and there is plenty of info about it available. – Cerbrus Feb 03 '14 at 08:23
  • i google it and i dont find any answer for sorting list of dictionary by a dictionary keys – Pnsadeghy Feb 03 '14 at 08:54

1 Answers1

2

You'll need a custom callback (aka comparerfunction) for the sorting. Something along the lines of 1:

array.sort( function (a,b) { return +a.value - +b.value; } );

1 I'm assuming value should be numeric and to be sure the sorting will be numeric the value property is explicitly converted to a number using +

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Those `+` aren't necessary because `String - String` is `String - +String`, which then means `String - Number` and a String subtracting a number will cast the String to a Number. – Derek 朕會功夫 Feb 03 '14 at 09:00