I have an array of data get from the server(ordered by date):
[ {date:"2012-8", name:"Tokyo"}, {date:"2012-3", name:"Beijing"}, {date:"2011-10", name:"New York"} ]
I’d like to :
- get the name of the first element whose date is in a given year, for example, given
2012, I needTokyo - get the year of a given
name - change the date of a
name
which data structure should I use to make this effective ?
because the array could be large, I prefer not to loop the array to find something
Since it appears that the data is probably already sorted by descending date you could use a binary search on that data to avoid performing a full linear scan.
To handle the unstated requirement that changing the date will then change the ordering, you would need to perform two searches, which as above could be binary searches. Having found the current index, and the index where it’s supposed to be, you can use two calls to
Array.splice()to move the element from one place in the array to another.To handle searches by name, and assuming that each
nameis unique, you should create a secondary structure that maps from names to elements:You can then use the
maparray to directly address requirements 2 and 3.Because the
mapelements are actually just references to thearrayelements, changes to those elements will happen in both.