Sorting associative arrays/object in javascript/jquery by the length of their values (longest to shortest) -
what best way sort associative array/object using javascript/jquery length of values? longest value shortest value, if value same alphabetical.
eg result:
name["mike"] = "sanders" name["mary"] = "smith" name["sharon"] = "chan"; name["xu"] = "wang"; name["john"] = "ho";
i have looked , looked , not find similar question.
thanks
try this
var name= []; name.push({ key: 'mike', value: 'sanders' }); name.sort(function(a,b) { var aval = a.value.tostring(); var bval = b.value.tostring(); if (aval.length === bval.length) { return aval.localecompare(bval); } else { return aval.length - bval.length; } }); alert(name[0].value); //ho alert(name[1].value); //chan alert(name[2].value); //wang alert(name[3].value); //smith alert(name[4].value); //sanders
Comments
Post a Comment