Slice and Splice, why doesn't this work?

Tell us what’s happening:

Hey everyone! I’m a little confused on why my code doesn’t work, I checked the solution and I noticed they add each element of the first array individually into the second, what I did, was add the whole first array in the position specified, and I do get, in this case, [4, 1, 2, 3, 5], but it seems that it’s incorrect, any help here would be appreciated!

Your code so far


function frankenSplice(arr1, arr2, n) {
  var arr2Copy=arr2.slice(0,arr2.length);
  arr2Copy.splice(n,0,arr1);
  return arr2Copy; 
}

console.log(frankenSplice([1, 2, 3], [4, 5], 1)); 

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice/

You don’t have to remove items from the first array. The challenge never asks that.

Consider the following example from the challenge:

frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2);

// Above Should return => ["head", "shoulders", "claw", "tentacle", "knees", "toes"] 

We take the first 2 items from the second array, prepend them to the first array, then concat them together like this:

["head", "shoulders"].concat(["claw", "tentacle"]).concat(["knees", "toes"])

So, if you notice from the above example, we would need to do the following steps:

  1. Make the copy of arr2. ( You’re doing fine there, but this would work too: var arr2Copy=arr2.slice(); Providing no arguments means to get a full copy of the array)
  2. Extract the first n items from the copied array using splice. (The returned item will be a sub-array)
  3. Concat them in order, extractedItems, arr1, copy2arr.
    cop2arr will be the remaining array after you’ve extracted the items.

If you reason about the above steps, they would make sense (given the nature of the current challenge)

If I can’t understand the challenge at first, I usually look what the return value has to be, and I start from there.

1 Like

check this in the browser console., you will see that it is a multidimensional array. you need a monodimensional array.

1 Like

Ah, of course! What I’m doing is adding the whole array into the first position, that’s why it isn’t working, thank you

Thank you! I’ll try this again when I get home