Reputation: 1
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
Upvotes: 0
Views: 1599
Reputation: 12688
i'd use flat and sort. Sort needs a sorting function if you want to sort by numerical vs string value.
const arr = [2, [12,5], [4, 22,14], 1,[6,8,7]];
const flattened = arr.flat().sort((a,b) => a-b);
console.log(flattened);
// Array [1, 2, 4, 5, 6, 7, 8, 12, 14, 22]
Upvotes: 0
Reputation: 207501
If built in methods you can do it with out making a copy of the array since flat already will spit out a new array.
const flatSort = arr => arr.flat().sort();
console.log(flatSort([3,2,4,1,5,6,7,8,9, 0]));
console.log(flatSort([2,[1,5],4,2,[6,8,7]]));
You could code your own flatting and sort/insertion code. Many algorithms out there, here is a simple one to get ideas rolling in your head.
function insertSort(arr, val) {
const len = arr.length;
let i = 0;
while(i < arr.length) {
if (arr[i] >= val) {
arr.splice(i, 0, val);
return;
}
i++;
}
arr.push(val);
}
const flatSort = (nestedArray, arr=[]) => {
nestedArray.forEach(val => {
if (Array.isArray(val)) {
flatSort(val, arr);
} else {
insertSort(arr, val);
}
});
return arr;
};
console.log(flatSort([3,2,4,1,5,6,7,8,9, 0]));
console.log(flatSort([2,[1,5],4,2,[6,8,7]]));
Upvotes: 0
Reputation: 105
I think this is the simplest.
let abc = [[3,1],[4,1,5],[9,[2,6]]];
let abc1 = abc.flat(); // [3,1,4,1,5,9,[2,6]];
console.log(abc1.sort()); // [1,1,[2,6],3,4,5,9];
If you were looking for a way to make it so the base array no longer had any arrays inside, it should include a for loop for either the contents of the base array to find which ones are still array, or use map() to change just the contents of the detailed arrays. The top example of flatMap() in this link will show how to do both in one function!
Upvotes: 0
Reputation: 11
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).
Upvotes: 0