I solved the Slice and Splice exercise after doing some research and going over the syntax for the slice and splice methods again. Below is my solution. Is that a good way to solve it, or are other ways more optimal? After solving it I looked at solutions from others and didn’t see anything very similar to mine, so just curious. Thanks in advance for any feedback.
function frankenSplice(arr1, arr2, n) {
let arr3 = arr2.slice(n, arr2.length);
let arr4 = arr2.slice(0, n)
let arr5 = arr4.concat(arr1);
let arr6 = arr5.concat(arr3);
return arr6;
}
console.log(frankenSplice([1,2,3], [4,5,6], 2));
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
Not optimal at all. You have to make a a for loop to add elements from array 3 and array 4 into array 1. This is because you need to add each element from array 3 from the beginning of array 1 and adding each element from array 4 to the end of array 1. The Concat function just end all the elements to the end.
Could you explain why a for loop is a better way to go though please? I know other solutions use a for loop, but I’m don’t understand the advantage of doing it that way vs this way.
@udaaff Thanks for the feedback. I’m brand new to programming and Javascript is the first language I’m trying to learn (other than CSS and HTML) so I’m not really sure the best way to do things…I’m just happy when I write something that actually passes the test lol.