2

I'm currently working on a pre-bootcamp course and haven't been able to find help online in order to solve a problem that has me a bit confused.

I understand when we use JavaScript we have push(), pop(), shift() and unshift() methods we can use in order to add/remove from an array. The problem I'm running into is the test question ask:

  1) Arrays appendKitten(name) appends a kitten to the kittens array and returns a new array,
     leaving the kittens array unchanged: 

I've been confused for nearly a day in solving this problem. I get when we do want to change the array we'll use one of the methods. For example when we append it'll be:

var kittens = ["Milo", "Otis", "Garfield"]

function destructivelyAppendKitten(name){
 kittens.push(name)
 return kittens
}

Which will push a new kitten(name) into the array. Now in order to solve the previous test I've written:

function appendKitten(name){
 var newArray = []
 var kittens = kittens.concat(newArray);
 kittens.push(name)
 return kittens
}

but continue to receive the same error. Is there something I'm missing?

My thought process in solving this question:

1- We are calling a function names appendKittens with a single argument -> name.

2- We are pushing data from the kitten variable into a local kitten instance in order to have the same array.

3- We push whatever name passes in the parameter into the new array.

4- Return the new array which had the push() performed leaving global kitten untouched.

Is my thinking process off? any ideas to where I'm off? All those who help. Thank you, really do appreciate it.

1 Answer 1

4
function appendKitten(name){
  var newArray = kittens.slice();
  // or ES6 way
  // var newArray = [...kittens];
  newArray.push(name)
  return newArray
}
Sign up to request clarification or add additional context in comments.

1 Comment

THANK YOU! I'll need to study the way you wrote it. I also really appreciate that you included ES6 for me to understand both. Glad to see I wasn't too off in my thinking. (I'll accept your answer in 7 minutes as stackoverflow is telling me to wait).

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.