I have a chain of methods that treat an array. Then I was trying to do a simple thing: add an element at the start of the array in a method chain. Initially I tried:
console.log(
[1, 2, 3]
.map(a=>a+1)
.splice(0, 0, 7)
.map(a=>a*10)
)
I used splice, because unshift returns the number of elements in the array. So hoped the result would be [70, 20, 30, 40]
, but the result was []
as splice returns the elements deleted in the array.
I give it a thought and couldn’t find any other way to do this. Not even with .apply.
That’s a simple thing I can easily solve by breaking the chain, but I thought it might be an oportunity to learn a bit (and don’t like to give up that easily :D), so searching a bit I found only one way to chain this:
console.log(
[2, 3, 4]
.map(a=>a+1)
.concat(7)
.map((e, i, a) => i == 0 ? a[a.length - 1] : a[i-1])
.map(a=>a*10)
)
I mean… really ? there should be a better way to chain a simple insert at first position. Anyone knows a better way ?
3
Answers
Based on the answers and comments, as I think that toSpliced() method is too new. I think I decided myself by:
There is also the slow but more readable option below.
Obviously toSpliced() method as @Palladium02 and @Bergi noted is far more readable and @AlexanderNenashev's answer the fastest by far. So depending on your need (readability, compatibility, speed or best of both worlds) you may choose any of the answers above.
You’re looking for the new
toSpliced
method which returns a new array with the modification applied (instead of mutating the receiver and returning the deleted elements):Of course there’s various alternatives to achieve what you want, like
.reverse().concat([7]).reverse()
, but they’re not very readable.I would suggest to avoid chaining and thus avoid intermediate arrays (
Array#reduce()
is a king):And benchmarking:
Open in the playground