0

I'm trying to write an append function, such that it does not mutate the input list:

append([ [1], [2] ], [3]) should equal [ [1], [2], [3] ].

I tried:

append = (arrayOfArrays, newElem) ->
  [first, remainder...] = arrayOfArrays
  [first, remainder.concat(newElem)]

but it does not work as intended:

append [[1],[2]], [3] == [[1],[[2],3]]

2 Answers 2

2

The reason why it's not working for you is:

  1. You are appending to the remainder, instead of the new array. And concat expects an array as parameter, which it will then combine with the other array
  2. As in your case the item to be appended using concat is an array, you need to nest it inside another array.

I would also advise using the slice(0) method to duplicate the initial array, and concat a new array to it, which contains the new array:

# Duplicate an array of arrays, and append a new array to it, returning the new array.
# @params list [Array<Array>] array of arrays
# @params newItem [Array] new array
# @return [Array<Array>] duplicate of array with new array appended to it
append = (list, newItem) ->
  list.slice(0).concat [newItem]

a = [[], [1,1], [2]]
append a, [3,3]
# => [[], [1,1], [2], [3,3]]
a
# => [[], [1,1], [2]]

Slice will make a copy of part of the array. slice(0) will start at the 0th index, and go to the end, effectively making a copy of the array.

Concat joins two arrays. But you want to keep the new array intact. Therefore you have to wrap it in another array which then gets merged into the main array.

Sign up to request clarification or add additional context in comments.

Comments

1

Since @caffeinated.tech beat me to the simple solution, here's an approach which doesn't use the slice trick. Unfortunately, this approach suffers from increased complexity, as you'll always need to traverse the entire collection.

append = (collection, member) ->
  collection.reduceRight (memo, member) ->
    memo.unshift member
    memo
  , [member]

existing_array = [[1], [2]]
existing_member = [3]
console.log(append(existing_array, existing_member)) # [[1], [2], [3]]
console.log(existing_array)                          # [[1], [2]]
console.log(existing_member)                         # [3]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.