Home > database >  How to flat an array of arrays and order it in javascript
How to flat an array of arrays and order it in javascript

Time:10-29

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

CodePudding user response:

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).

CodePudding user response:

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!

CodePudding user response:

i'd use flatMap and sort

const arr = [2,[1,5],4,2,[6,8,7]]
const flattened = arr.flatMap(num => num).sort();
console.log(flattened);

// Array [1, 2, 2, 4, 5, 6, 7, 8]
  • Related