arrays - How to implement a map or sorted-set in javascript -


javascript has arrays use numeric indexes ["john", "bob", "joe"] , objects can used associative arrays or "maps" allow string keys object values {"john" : 28, "bob": 34, "joe" : 4}.

in php easy both a) sort values (while maintaining key) , b) test existence of value in associative array.

$array = ["john" => 28, "bob" => 34, "joe" => 4];  asort($array); // ["joe" => 4, "john" => 28, "bob" => 34];  if(isset($array["will"])) { } 

how acheive functionality in javascript?

this common need things weighted lists or sorted sets need keep single copy of value in data structure (like tag name) , keep weighted value.

this best i've come far:

function getsortedkeys(obj) {     var keys = object.keys(obj);     keys = keys.sort(function(a,b){return obj[a]-obj[b]});      var map = {};     (var = keys.length - 1; >= 0; i--) {       map[keys[i]] = obj[keys[i]];     };      return map; }  var list = {"john" : 28, "bob": 34, "joe" : 4}; list = getsortedkeys(list); if(list["will"]) { } 

looking @ this answer luke schafer think might have found better way handle extending object.prototype:

// sort value while keeping index object.prototype.iteratesorted = function(worker, limit) {     var keys = object.keys(this), self = this;     keys.sort(function(a,b){return self[b] - self[a]});      if(limit) {         limit = math.min(keys.length, limit);     }      limit = limit || keys.length;     (var = 0; < limit; i++) {         worker(keys[i], this[keys[i]]);     } };  var myobj = { e:5, c:3, a:1, b:2, d:4, z:1};  myobj.iteratesorted(function(key, value) {     console.log("key", key, "value", value) }, 3); 

http://jsfiddle.net/xeoncross/kq3gbwgh/


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -