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