Search⌘ K

Solution Review: Insert Elements

Explore how to fix common issues when inserting elements into an array in JavaScript. Understand the use of the splice method and the spread operator to insert individual elements correctly, ensuring an updated array without nested structures.

We'll cover the following...

The challenge in the previous lesson requires you to fix the following code using your understanding of the .splice function.

Javascript (babel-node)
function solSplice(array1, array2, n) {
return array2.splice(n,0,array1)
}
console.log(solSplice([1, 2, 3],[4,5,6],1))
console.log(solSplice([8,9,10],[11,12,13],2))

Explanation

The original code has two issues that need fixing; let’s take a look at them one by one.

Issue 1

The first change we make is the line 2 of the code.

  return array2.splice(n,0,array1)

The splice method is used to add/remove items from an array. It returns an array with any elements that were removed. It ...