I am currently extracting data from a database, and here is a simplified representation of the information:
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}
];
My goal is to dynamically sort this data into a new empty array called newArr
. After sorting is completed, newArr
should be arranged as follows:
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}
]];
As someone who is new to JavaScript, I chose to work with arrays and objects due to the importance of object order in JSON data.
My Approach and Attempts
I have been attempting to group objects based on different keys within the main array (newArr[0], newArr[1], etc.). During iteration over example
, if the end
property is lower than what is already present in newArr, an overlap occurs, resulting in the creation of a new array. Otherwise, the object should be pushed into the appropriate key without overlap. Below are the three functions I've tried for this process:
var newArr = [];
function _overlap(){
// place first object
var addFirst = [example[0]];
newArr.push(addFirst);
// place others, starting with i = 1;
for (var i = 1 ; i < example.length ; i++){
_checkOverlap(example[i]);
}
}
_overlap();
function _checkOverlap(input){
loopJ:{
for (var j = 0; j < newArr.length; j++){
var innerArrayLength = newArr[j].length;
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);
}
While this code successfully sorts the first key (newArr0) as intended, it fails to push elements into other keys. I am considering implementing recursion, but multiple crashes due to infinite loops have made this process challenging. Any insights or suggestions would be greatly appreciated.