0

I am using an associative array to reflect a list of LI elements:

var array = []
array["cats"] = {k: "cats", v: "meow"};
array["dogs"] = {k: "dogs", v: "woof"};
array["mice"] = {k: "mice", v: "eek"};

I need to keep the order of the array elements to match the order of the LI elements. if I reorder the LI elements (e.g. move mice to the 2nd position in the list), I want to reorder the array so that I can do the following and see the the same order:

for (var i in array){
    console.log(i);
}

and produce the output:

cats
mice
dogs

Since it is associative, I cannot use the splice method. How can I accomplish this?

mseifert
  • 5,390
  • 9
  • 38
  • 100

1 Answers1

0

You can't do it, there are no associative arrays in JavaScript - those are object (without ordering) and that's just a way of representing them. obj.something is equal to obj['something'].

To keep the ordering, I suggest you use an array of objects:

var arr = [{k: "cats", v: "meow"}, {k: "dogs", v: "woof"}, {k: "mice", v: "eek"}];

Arrays can be ordered.

Shomz
  • 37,421
  • 4
  • 57
  • 85
  • I am not used to "can't do" answers. I'm surprised by the limitation but it seems like I have 3 choices: 1) Take out the index from my current array, which is what your answer does, 2) add a 'position' property to the object which I can process 3) add a second parallel array sorted in the correct order. I will choose option #2 as it will serve my purposes best. Thanks for the reply. – mseifert Jan 30 '16 at 04:28
  • Sorry, it shouldn't be just "can't do", but rather "can't do with objects" simply because they don't have a notion of order. I also think that everything's possible. :) The "position" property will serve you well, but for things like performance, or easy rendering of the elements (by just using the regular for loop), I'd go with my answer - making that array an actual representation of those element. You're welcome! – Shomz Jan 30 '16 at 11:51