0

I have an array and I need to sort it in desc order, but it doesn't seem to work. What could I fix?

var array = [];
array['a'] = ['1','2','3'];
array['b'] = ['2','3'];
array['c'] = ['5','6','8','9'];

  

array.sort(function(a, b) {
 return a.length < b.length ? -1 : (a.length > b.length ? 1 : 0);
});

console.log(array);
Aerodynamika
  • 7,883
  • 16
  • 78
  • 137
  • 5
    `array['a']` ?? Arrays should have *numeric* indicies – CertainPerformance Feb 03 '19 at 09:58
  • Arrays in JavaScript cannot have string keys. JavaScript is not PHP. You can use an object `{}`, but those are not sortable. – Madara's Ghost Feb 03 '19 at 09:58
  • 2
    arrays can have keys, as they are objects, but it not advisable to use them. – Nina Scholz Feb 03 '19 at 09:59
  • In my code it works to have string keys. I use them to be able to look up the right array quicker, as with an array I can simply go `array[whatimlookingfor]` and i get the value without having to iterate through an object. – Aerodynamika Feb 03 '19 at 10:00
  • the special feature of an array is to use it with indices and the items are sortable. for what you want ios to use na object and get the keys sorted for an access by the wanted order. – Nina Scholz Feb 03 '19 at 10:03
  • 2
    "it works" is not a valid explanation because of a lot weird things work in javascript (Like: `[] + {} === {} + []`). It is bound to create an issue later for you or some unfortunate soul using this code. You can create an object with each keys pointing to an array llike this if you want bracket notation accessor: `{"a": ['1','2','3'], "b": ['2','3']}` – adiga Feb 03 '19 at 10:03

1 Answers1

1

What could I fix?

Your array is empty, as it doesn't have numeric keys. Therefore sorting it does nothing, when logging you see the non-numeric keys in the array.


As you want fast lookup you need a hashtable (object or Map) however, they are not sorted, so you also need an array to have a sorted order. You could easily build both for your data:

const lookup = {
  a: [ '1','2','3'],
  b: ['2','3'],
  c: ['5','6','8','9'],
};

const sorted = Object.values(lookup).sort((a, b) => a.length - b.length);

console.log(
  lookup["a"], 
  sorted[0]
);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151