0

I have a very common scenario where I want to iterate over, and query an associative array in JS and also be able to maintain it's order based on an array item property such as 'id' or 'display_order'. I also want to be able to push and pop based on that property.

Has anyone written a object type that behaves like both an associative and normal array? Something like

var startingArray = [
   {name: 'thingy',
   order: 1}
 {name: 'thinger',
   order: 3},
{name: 'thang',
   order: 2}
}
]

new superArray(startingArray, 'order');

console.log(superArray[2])// {name: 'thang', order: 2}

superArray.push({name:'thangeroo', order:34})

console.log(superArray[34])// {name: 'thangeroo', order: 34}

superArray.forEach((thing) =>{
   console.log(thing) // this would always iterate in order based on 'order'
})

superArray.pop()//removes {name: 'thangeroo', order: 34}

for(var k in superArray){
  var thing = superArray[k] // this seems less important but still useful
}

I can imagine how this would be done, but I wanted to see if there are good implementations I could use or maybe explanations on why this is a bad idea or not. If you're wondering, I'm using this to manipulate and display data in a flux-alt-react context.

Update

I found exactly what I was looking for: https://facebook.github.io/immutable-js/docs/#/OrderedMap

user1204800
  • 46
  • 1
  • 6
  • 2
    What's wrong with just [`sorting`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) the array? – Emissary Apr 07 '16 at 18:16
  • How about using lodash? – Molda Apr 07 '16 at 18:16
  • @Emissary Needing to maintain iteration order *and* reference by id (or order in my example) is what I'm trying to do. Sorting would fix the first one, but not the second. I know there are obvious ways to select an array item by a property, but I'm looking for clean implementations that might actually work with standard(ish) syntax. – user1204800 Apr 07 '16 at 18:22
  • @Molda oooh, I like what I'm seeing in lodash. – user1204800 Apr 07 '16 at 18:23
  • Updated question with an answer. – user1204800 Apr 11 '16 at 23:01

0 Answers0