Slice and Splice help

Tell us what’s happening:
I did a very basic solution to this but i wish to know how could i have solved it using slice and splice both as i have used only splice(). (I don’t get slice() properly.)
Any other approach is totally welcome.

Your code so far


function frankenSplice(arr1, arr2, n) {
  // It's alive. It's alive!
   var newArr = [];
   newArr.push(...arr1);
    var newArr2 = [];
  newArr2.push(...arr2);
  newArr2.splice(n,0,...newArr);
  return newArr2;
}

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/68.0.3440.84 Safari/537.36.

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

Instead of the above

Var newArr = arr1.slice();

Imagine a loaf of bread (and english loaf of bread). You want to “slice” it. If you slice the whole loaf you end up still having the whole loaf but in pieces right? That’s essentially what slice does if you give it zero arguments. If you give it some arguments it returns a new array with a section (some slices) of the old array.

So that is what slice does. You coud combine slice and splice together to chain them and copy the array then splice the other array into it at the correct spot.

Ps. I should point out that you could have used spread more concisely as well like this
let newArr=[…arr1];

2 Likes

my solution was something like this

function frankenSplice(arr1, arr2, n) {
  return arr2.slice(0, n).concat(arr1, arr2.slice(n, arr2.length));
}

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

Btw here can be used slice and splice together, idk for what but…may be for practice

function frankenSplice(arr1, arr2, n) {
  return [...arr2].splice(0, n).concat(arr1, arr2.slice(n, arr2.length));
}

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

function frankenSplice(arr1, arr2, n) {
// It’s alive. It’s alive!
var newarr1 = […arr1];
var newarr2 = […arr2];
newarr2.splice(n, 0, …newarr1.slice());
return newarr2;
}

[spoiler]function frankenSplice(arr1, arr2, n) {
// It’s alive. It’s alive!
var newArr=[];
newArr=arr2.slice(0);
newArr.splice(n,0,…arr1);
return newArr;
}

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