Is there a better way to flat an array of arrays of integers? this solution is easy but I really don't know if it's time complexity is the best.
const list = (arr) => {
//to avoid mutating the the entry data
let newArr=[...arr]
return newArr.flat().sort((a,b)=>a-b)
}
// this logs [1,2,2,4,5,6,7,8]
console.log(
list([2,[1,5],4,2,[6,8,7]])
)
I think maybe with reduce I can both flat the array and order it?
I'm trying to get a better performance at my algorithm
There's not really a better way to flatten and sort integers; the only way to get better time complexity is to use a different sorting algorithm, since the default Javascript algorithm is merge sort, which has O(nlogn) complexity. Here's the Wikipedia page for integer sorting algorithms that shouldn't be too difficult to implement.
I don't know what the range of your integers are, but if it's really small, you might want to just do counting sort (time complexity O(n)) since it's kind of easy to implement (GeeksForGeeks has an implementation). But, if you only have a few numbers that have a large range, you could do radix sort (time complexity varies: could be as low as O(n) -- depends on parameters used).