Sort Multi-dimensional associative arrays in javascript by range -


i trying sort multi-dimensional array returned api allow people choose range based on beats.

to honest stuck api returns.

var myobj = [{     title: 'title one',     beats: 1 }, {     title: 'title two',     beats: 2 }, {     title: 'title three',     beats: 3 }, {     title: 'title four',     beats: 4 }, {     title: 'title five',     beats: 5 }, {     title: 'title six',     beats: 6 }, {     title: 'title seven',     beats: 7 }, {     title: 'title eight',     beats: 8 }, {     title: 'title nine',     beats: 9 }, {     title: 'title ten',     beats: 10 }]; 

now trying allow users select range based on beats.

so if select 1-4 return.

var myobj = [{     title: 'title one',     beats: 1 }, {     title: 'title two',     beats: 2 }, {     title: 'title three',     beats: 3 }]; 

and 8-10 return etc etc...

var myobj = [{     title: 'title eight',     beats: 8 }, {     title: 'title nine',     beats: 9 }, {     title: 'title ten',     beats: 10 }]; 

what function use appreciate on this?

@qubyte's answer how properties values of javascript object (without knowing keys)?

tells how enumerate on values of returned object.

for (var key in obj) {     if (obj.hasownproperty(key)) {         var val = obj[key];         // use val     } } 

in example, each value in returned myobj object properties "title" , "beats", , want search entire myobj have particular beats.

let's start making function searches on properties of values, , returns array having desired values.

function searchbyproperty(obj, property, low, high){   var found = [];   var val, prop;   (var key in obj) {     if (obj.hasownproperty(key)) {         val = obj[key];         prop = val[property];         if( (prop>=low) && (prop<=high) ) found.push(val);     }   return found; } 

now can use this:

   searchbyproperty(myobj, 'beats', 1, 4) 

will return:

[     {         title: 'title one',         beats: 1     },     {         title: 'title two',         beats: 2     },     {         title: 'title three',         beats: 3     },     {         title: 'title four',         beats: 4     } ] 

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -