DEV Community

D\sTro
D\sTro

Posted on

Javascript array sort with Reducer

Alt Text

This has been the most tricky/confusing javascript interview question for starters specially ๐Ÿ˜€

And this was my answer once which made interviewer shy: how the hell candidate will know if interviewer has speech recognition issue..

Btw, instead forloop, you can use "reducer" like this โคต๏ธ

//

 let reducer = (acm, value) => { const nextIndex = acm.findIndex(i => value < i ); const index = nextIndex > -1 ? nextIndex : acm.length; acm.splice(index, 0, value); return acm; } // execution Ley arr = [ arr.reduce(reducer, []) will produce [1,2,3,4] 
Enter fullscreen mode Exit fullscreen mode

Let me know how you answered this kind of interviews

Thanks!

Top comments (5)

Collapse
 
tiagojpdias profile image
Tiago Dias

What??

[6,3,-1,2].sort() // [ -1, 2, 3, 6 ] 
Enter fullscreen mode Exit fullscreen mode

Which is completely fine. I think you missed the point here...

Array.prototype.sort accepts a callback as a custom sorter.

What a convoluted piece of "code". Awful use case to make your point across.

Collapse
 
orgimeno profile image
Oscar Rodriguez Gimeno

They asked me how to center a div. I told them 'margin 0 auto' although I don't know if it works in iexplorer

Collapse
 
slimdestro profile image
D\sTro

๐Ÿ˜€๐Ÿ‘Œ

Collapse
 
alfredosalzillo profile image
Alfredo Salzillo

Please ad the javascript tag to the code block.

Collapse
 
slimdestro profile image
D\sTro

thanks