DEV Community

Discussion on: How not to sort an array in JavaScript

Collapse
 
pheeria profile image
Olzhas Askar

I think the biggest disadvantage of sort() is that it sorts in place.
You need to do some relatively ugly hacks like spreading:

[...array].sort().map(console.log)

in order to use the power of FP.

Collapse
 
philnash profile image
Phil Nash

Yeah, it is a shame that it acts in place as we move to code that attempts to reduce the number of side effects. At least we can work around it, the problem is just remembering to.

Collapse
 
zhuangya profile image
zhuangya

it returns an array of undefineds :/

Collapse
 
damon profile image
damon

That's because the console.log returns undefined, and it's being used in the call to .map().

var array = [9, 2, 3, 8, 1, 0]
var orderedArray = [...array].sort()

console.log(array)
// [9, 2, 3, 8, 1, 0]
console.log(orderedArray)
// [0, 1, 2, 3, 8, 9]

var logReturn = console.log("hello world")
// hello world
console.log(logReturn)
// undefined
Thread Thread
 
zhuangya profile image
zhuangya

exactly, my point is we should not use map here at all.