Javascript : looping array of arrays. If match found, push to array, if not, create new innerarray -
i'm retrieving information database. data looks (i've simplified it):
var example = [ {'start': 1966, 'end': 1970}, {'start': 1969, 'end': 1971}, {'start': 1972, 'end': 1980}, {'start': 1974, 'end': 1985}, {'start': 1975, 'end': 1979}, {'start': 1986, 'end': 1990}, {'start': 1991, 'end': 1995} ];
what want sort dynamically new, empty array newarr
. when sorting done newarr
should like
var newarr = [ [ {'start': 1966, 'end': 1970}, {'start': 1972, 'end': 1980}, {'start': 1986, 'end': 1990}, {'start': 1991, 'end': 1995} ], [ {'start': 1969, 'end': 1971}, {'start': 1974, 'end': 1985} ], [ {'start': 1975, 'end': 1979} ]];
i'm new javascript. reason i've chosen combination of arrays , objects because i'm using json data in order of objects important
what want , tried
i'm trying group objects on different keys of main array (newarr[0], newarr[1] etc . want iterate through example
, put objects on key. if in iteration of example property end
lower @ moment on newarr, there overlap , new array should made. else should pushed in main array key where there no overlap. i've tried doing the following 3 functions
var newarr = []; function _overlap(){ // place first object var addfirst = [example[0]]; newarr.push(addfirst); // place others, therefore start = 1; (var = 1 ; < example.length ; i++){ _checkoverlap(example[i]); } } _overlap(); function _checkoverlap(input){ // traverse main array newarr, example[i] passed argument input loopj:{ (var j = 0; j < newarr.length; j++){ // compare value of input.start (so example[i]) last key of inner array var innerarraylength = newarr[j].length; // need last key: length -1 if (input.start > newarr[j][innerarraylength-1].end ){ newarr[j].push(input); console.log(newarr); break loopj; } else { _createnewarr(input); break loopj; } } } } function _createnewarr(input){ var tobeadded = []; tobeadded.push(input); newarr.push(tobeadded); }
this code want on first key newarr0 , never pushes other keys. should use recursion in case? i've tried many things, amount of browsers crashes due infinite loops driving me crazy.
if understand correctly, each entry of example
must search first group in newarr
entry can added. if find group, add entry , iterate next entry. if don't find group, create new group @ end.
var newarr = []; outerloop: for(var entry of example) { for(var group of newarr) if(group[group.length-1].end < entry.start) { group.push(entry); continue outerloop; } newarr.push([entry]); }
Comments
Post a Comment