coffeescript - Append Array to Array of Arrays -
i'm trying write append
function, such not mutate input list:
append([ [1], [2] ], [3])
should equal [ [1], [2], [3] ]
.
i tried:
append = (arrayofarrays, newelem) -> [first, remainder...] = arrayofarrays [first, remainder.concat(newelem)]
but not work intended:
append [[1],[2]], [3]
== [[1],[[2],3]]
the reason why it's not working is:
- you appending
remainder
, instead of new array. ,concat
expects array parameter, combine other array - as in case item appended using
concat
array, need nest inside array.
i advise using slice(0)
method duplicate initial array, , concat new array it, contains new array:
# duplicate array of arrays, , append new array it, returning new array. # @params list [array<array>] array of arrays # @params newitem [array] new array # @return [array<array>] duplicate of array new array appended append = (list, newitem) -> list.slice(0).concat [newitem] = [[], [1,1], [2]] append a, [3,3] # => [[], [1,1], [2], [3,3]] # => [[], [1,1], [2]]
slice make copy of part of array. slice(0)
start @ 0th index, , go end, making copy of array.
concat joins 2 arrays. want keep new array intact. therefore have wrap in array gets merged main array.
Comments
Post a Comment