Slice and Splice Problems

Slice and Splice Problems
0

#1

Tell us what’s happening:
I’m going through the basic algorithm challenges, and I’m not sure why I’m not passing. Here’s my code so far:

Your code so far


function frankenSplice(arr1, arr2, n) {
  var arr3 = arr2;
  for (var i = 0; i < arr1.length; i++) {
     arr3.splice( n, 0, arr1.slice(i,i+1));
     n++;
  }
  console.log(arr3);
  return arr3;
}

frankenSplice([1, 2, 3], [4, 5, 6], 1);

Your browser information:

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

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


#2

Three things:

  1. In Javascript, Arrays and Objects are passed by reference. So, you are saying in the first line that arr3 and arr2 are variables that point at the same Array object. When you splice into arr3, you are ALSO splicing into arr2. Run this code and check the console to see what I mean:
function frankenSplice(arr1, arr2, n) {
  var arr3 = arr2;
  for (var i = 0; i < arr1.length; i++) {
     arr3.splice( n, 0, arr1.slice(i,i+1));
     n++;
  }
  console.log("+++++\n","arr1\n", arr1,"\narr2\n", arr2, "\nn: ",n);
  console.log("arr3");
  console.log(arr3);
  return arr3;
}
  1. I can’t figure out why you have a for loop at all. Functional programming is supposed to make you not need for loops to iterate over arrays.
  2. You should look at the console for (1), and ask why you have nested arrays in your output. The answer is on MDN’s page for splice. Visit that, and check out the left navbar to get a better idea of the inputs and outputs for splice as well. I love and live on MDN. One of my four screens ALWAYS has it up.

#3

Thanks, but I don’t get nested arrays. Here’s my output:

+++++
,arr1
,1,2,3,
arr2
,4,1,2,3,5,
n: ,4
arr3
4,1,2,3,5

#4

Why withdraw the post? Leaving it up makes it searchable as people type in their own questions. It helps others to see the problem already addressed.


#5

Got it…Kind of. VS Code to the rescue! I love the debug console now. Going to look at MDN now.


#6

I caved and looked at the answer. I should’ve seen it! :grin:


#7

If you want more practice, I’m sure you could hunt down some practice problems with google.