How to flatten a 2D array into a sorted one-dimensional array in TypeScript

1 Answer

0 votes
// Function that flattens a 2D number array and returns a sorted 1D array
function flattenAndSort(array2d: number[][]): number[] {

    // Flatten the 2D array into a single array
    // .flat() defaults to depth 1, which is perfect for 2D arrays
    const flattened: number[] = array2d.flat();

    // Sort numerically (default sort is lexicographic)
    return flattened.sort((a, b) => a - b);
}

const array2d: number[][] = [
    [4, 5, 3],
    [30, 20],
    [10],
    [1, 2, 6, 7, 8],
];

const arr: number[] = flattenAndSort(array2d);

// Print result as comma‑separated values
console.log(arr.join(", "));



/*
run:

1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30


*/

 



answered 2 hours ago by avibootz

Related questions

...