# Slice and Splice Exercise - Good Solution?

Hello Everyone,

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.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

1 Like

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.

# Slice and Splice

You are given two arrays and an index.

Copy each element of the first array into the second array, in order.

Begin inserting elements at index `n` of the second array.

Return the resulting array. The input arrays should remain the same after the function runs.

This is a correct algorithm, but you may write it much shorter, without creating even a single variable, and also it’s hard to read such a code.

@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.

Getting things passing is always an important first step.

Writing the code so that it is clear to someone else 6 months from now is a great second step to focus on.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.