4 ms·
Some more practical examples // Grab unique [1,1,2,3,4].filter( ( item, index, array ) => array.indexOf( item ) === index ) // => [1,2,3,4] /
by drinchev 9y ago
Some more practical examples
// Grab unique
[1,1,2,3,4].filter( ( item, index, array ) => array.indexOf( item ) === index )
// => [1,2,3,4]
// Flatten
[[1,2],[3,4]].reduce( ( result, item ) => result.concat(item), [] );
// => [1,2,3,4]
Not sure why the author missed `sort`.
// Sort
[1,2,4,3].sort( ( a, b ) => a - b )
- Veedrac 9y agoThe first is slow (O(n²) where O(n) will do), and the second is very likely to be slow (probably the same).
- drinchev 9y agoThe good old question about sacrificing performance for readability. Anyway these days filter is not so bad. [1] https://jsperf.com/array-uniq-filter https://jsperf.com/array-uniq-filter
- Veedrac 9y agoAnd insertion sort is not so bad with 20 elements. It doesn't take much for it to start falling over, though. [1]: https://jsperf.com/array-unique-filter-2/1 https://jsperf.com/array-unique-filter-2/1
- _ar7 9y agoIf you wanted to do O(n) functionally, you could do [1, 1, 2, 3, 4].filter( (obj => x => { if (obj[x]) { return false; } obj[x] = true; return true; })({}), ); What's happening is that you're passing an object (hashmap / hashset) into a function that returns a filtering function, and that object is used inside the closure to track the dupes. It's still a pure function because even though you're mutating the passed in object, the filtering function is still deterministic and referentially transparent.
- zabana 9y agoAuthor here, thanks for your feedback ! I didn't mention sort because I thought I (personally) rarely use it and wanted to provide examples of more widely used array methods (namely filter reduce and map).
- deleted 9y ago[deleted]
- andreareina 9y agoArray.prototype.sort destructively modifies the array, which is typically not considered a part of the functional paradigm. You could make a case for pragmatism if the array were purely local to the function (i.e. not passed into it), so that nothing outside the function would notice anything being mutated.
- purple-dragon 9y agoFor unique, I prefer to let javascript do the work: // Grab unique [...new Set([1,1,2,3,4])]
- _ar7 9y agoAlthough it wouldn't work if you were using objects and wanted to do a deep comparison e.g. [...new Set([{x: 1}, {x: 1}])]
- purple-dragon 9y ago... an important observation, for sure.
- AndrewStephens 9y agoYeah, I recently did a project in Javascript (as a longtime C++ programmer) and was bitten by this exact problem. Javascript is great but sometimes I miss the predicability of the STL.