-2

I have an array and when I console.log it it give me this:

[paris: 348589.40826358093, londres: 490078.8871883664, nantes: 6363.461319105993] 

I want to sort the array by the value (the number), be I can't figure how to do it. i want a result order by the value like this: [nantes: 6363.461319105993, paris: 348589.40826358093, londres: 490078.8871883664] I have try with something like this but it's not working.

function compare(x, y) {
  return x - y;
}
tab.sort(compare);
TotuDoum
  • 137
  • 2
  • 11
  • 3
    your array is wrong declared. – King King Oct 11 '14 at 18:50
  • possible duplicate of [Sorting objects in an array by a field value in JavaScript](http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript) – Paul Roub Oct 11 '14 at 18:51
  • 2
    That's not an array. It's not even valid JavaScript. – JLRishe Oct 11 '14 at 18:54
  • Have read [here](http://blog.xkoder.com/2008/07/10/javascript-associative-arrays-demystified/) to find out more about associative arrays and what Javascript syntax should be used with them. – Bart Platak Oct 11 '14 at 18:56

2 Answers2

0

This array declaration is wrong. If you want to use name for items you should use js objects like below code.

var tab = {paris: 56765, londres: 3456546, 'new york': 25455654}

or

var tab = [{paris: 56765}, {londres: 3456546}, {'new york': 25455654}]

But if you want to have sort by that compare function, do something like this:

var tab = [{name: paris, value: 56765}, {name: londres, value: 3456546}, {name: 'new york', value: 25455654}]

and change compare method to this:

function compare(x, y) {
  return x.value - y.value;
}

If you want to have more condition in your js object can use this js library.

mhdrad
  • 330
  • 3
  • 15
-1

Array.prototype.sort()

Objects can be sorted given the value of one of their properties.

    var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic' },
  { name: 'Zeros', value: 37 }
];
items.sort(function (a, b) {
  if (a.name > b.name) {
    return 1;
  }
  if (a.name < b.name) {
    return -1;
  }
  // a must be equal to b
  return 0;
});

That should give you the idea

przno
  • 3,476
  • 4
  • 31
  • 45
  • that's not what i whant. i want to sort my array by the value which is the numbers. By what I understand this can only sor by name in your exemple – TotuDoum Oct 11 '14 at 19:00