I have some arrays, each of which can consist of a number of sub arrays or objects. For example
var array = [{id: 1, gpa: 3.11}, [{id: 2, gpa: 2.9}, {id: 11, gpa: 3.9}, [{id: 9, gpa: 2.11}]], {id: 7, gpa: 3.31}]
What I want to do is to flatten the elements of this array into one level, so it will be as follows:
[{id: 1, gpa: 3.11}, {id: 2, gpa: 2.9}, {id: 11, gpa: 3.9}, {id: 9, gpa: 2.11}, {id: 7, gpa: 3.31}]
Then order them by gpa:
[{id: 11, gpa: 3.9}, {id: 7, gpa: 3.31}, {id: 1, gpa: 3.11}, {id: 9, gpa: 2.11}, {id: 2, gpa: 2.9}]
Currently, the way I am using is as follows
function search(arr, obj){
if(Array.isArray(obj)){
arr.forEach(sub=>search(arr, sub));
}else{
arr.push(obj);
}
}
var array = [{id: 1, gpa: 3.11}, [{id: 2, gpa: 2.9}, {id: 11, gpa: 3.9}, [{id: 9, gpa: 2.11}]], {id: 7, gpa: 3.31}];
var flatten = [];
search(flatten, array);
console.log(flatten);
Then, I use a sort comparator to sort flatten.
Is there a better way to do that using the builtin methods of Javascript?