DevAcademy
LearnJavaScriptTransforming Arrays
IntermediateJavaScript

Transforming Arrays

Learn how to reshape arrays using sort(), reverse(), flat(), flatMap(), and join() — including mutation behavior, comparator functions, and common pitfalls.

Reading Time

20 min

Lesson

Lesson 20 of 48

Introduction

Beyond adding, removing, searching, and iterating, JavaScript also gives you methods that reshape an array's overall structure or presentation — reordering it, flattening nested arrays, or turning it into a string. Two of these methods, sort() and reverse(), mutate the original array in place, which surprises a lot of developers coming from map() and filter(). The others, flat(), flatMap(), and join(), are non-mutating and return something new. Knowing which category each method falls into is essential for avoiding accidental bugs in your data.

Methods Overview

MethodPurposeReturnsModifies Original Array
sort()Reorder elementsThe same array, sorted✅ Yes
reverse()Reverse the order of elementsThe same array, reversed✅ Yes
flat()Flatten nested arraysNew, flattened array❌ No
flatMap()Map then flatten one levelNew array❌ No
join()Combine elements into a stringA string❌ No

sort()

The sort() method reorders the elements of an array in place and also returns a reference to that same array. By default, sort() converts elements to strings and compares their UTF-16 code units — this means numbers are sorted as if they were text, so [10, 2, 30].sort() surprisingly produces [10, 2, 30] sorted as strings, giving [10, 2, 30] → ["10", "2", "30"] → [10, 2, 30] is wrong; the correct output is [10, 2, 30] sorted alphabetically as strings, resulting in [10, 2, 30]. To sort correctly, always pass a comparator function: (a, b) => a - b for ascending numbers, or (a, b) => b - a for descending. The comparator should return a negative number if a should come first, a positive number if b should come first, and 0 if their order doesn't matter.

sort() Example — The Default Trap

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

sort() Example — Using a Comparator

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

reverse()

The reverse() method reverses the order of the elements in an array in place, meaning the last element becomes the first and vice versa, and it returns a reference to the same, now-reversed array. Because it mutates directly, if you need to keep the original order intact elsewhere, copy the array first — for example with [...array].reverse() or array.slice().reverse() — rather than calling reverse() on the original.

reverse() Example

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

flat()

The flat() method creates a new array with all sub-array elements concatenated into it, up to a specified depth. By default, flat() only flattens one level deep; passing a number as an argument flattens that many levels, and passing Infinity flattens arrays of any depth, no matter how deeply nested. flat() does not mutate the original array — it returns a brand new, flattened one. It's especially useful for cleaning up data that comes back nested from an API or from grouping operations.

flat() Example

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

flatMap()

The flatMap() method first runs a map() callback on every element, then flattens the result by exactly one level — combining two common operations into a single, slightly more efficient method call. It's especially handy when your mapping callback itself returns an array for some or all elements, since a plain map() in that situation would leave you with an array of arrays that you'd then need to flatten yourself.

flatMap() Example

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

join()

The join() method combines every element of an array into a single string, separated by whatever separator string you provide as an argument (a comma by default if you omit it). Unlike the other methods on this page, join() doesn't return an array at all — it returns a plain string. It's the natural counterpart to String.prototype.split(), which turns a string into an array; join() takes an array back to a string.

join() Example

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Watch Out for Mutation

sort() and reverse() are the two methods in this lesson that change the original array — everything else (flat(), flatMap(), join()) leaves it untouched and returns something new. If you're working with state you shouldn't mutate directly (like React state), always make a copy first with the spread operator, e.g. const sorted = [...original].sort(...), rather than calling sort() or reverse() on the state array itself.

Important

Never call sort() without a comparator function when working with numbers — the default string-based comparison will silently produce wrong results without throwing any error, which makes this bug especially easy to miss in testing. Always use (a, b) => a - b (or the reverse) for numeric sorts, and a comparator based on the relevant property when sorting arrays of objects.

Interview Questions

Quick Quiz

1. What is wrong with calling [40, 1, 5, 200].sort() without a comparator?

2. Which of these methods does NOT mutate the original array?

3. What argument would you pass to flat() to flatten an array of any nesting depth?

4. What does flatMap() do differently from map()?

5. What does join() return by default if no separator is provided?