1

My question is about the output of this program: in the FCC (freecodecamp) console I see 4,3,2,1,5, whereas in the node console I see [ 4, 3, 2, 1, 5 ](same with the other arrays).

I also tried this at the line number 8: let result = array2Copy.map(i => i.toString());

function frankenSplice(arr1, arr2, n) {
  let array2Copy = arr2.slice(0);

  for (let i = 0; i < arr1.length; i++){
    array2Copy.splice(n, 0, arr1[i]);
  }
  let result = array2Copy;  

  return array2Copy;
}

console.log(frankenSplice([1, 2, 3], [4, 5], 1));-->4,3,2,1,5
console.log(frankenSplice([1, 2], ["a", "b"], 1));-->a,2,1,b

According with the FCC console, I need the following output: [4, 1, 2, 3, 5]

1
  • Take a look at MDN. You probaly can't use some functions as tools tolve problems if you don't know how they work in the first place. Specifically, look at what those function expect to get as arguments and what exacly they return. Commented Oct 2, 2019 at 22:15

1 Answer 1

3

First keep in mind that splice's arguments are:

  • (1) Index at which items should be added/removed
  • (2) Number of items to be removed
  • (3), (4), (5), ... (optional) Items to add

You need to insert one array into another, so all you need is a single splice: the index to insert the items at is the argument n, and you don't want to remove any items, so the second argument should be 0, and then to specify the items to add, just spread into the rest of the splice argument list:

function frankenSplice(arr1, arr2, n) {
  // don't mutate the argument
  const newArr = arr2.slice();
  newArr.splice(n, 0, ...arr1);
  return newArr;
}

console.log(frankenSplice([1, 2, 3], [4, 5], 1)); //-->4,3,2,1,5
console.log(frankenSplice([1, 2], ["a", "b"], 1)); //-->a,2,1,b

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.