Ben Jenney
Ben Jenney

Reputation: 75

I do not understand why .splice() is returning an empty array here

Would appreciate some feedback. I read the MDN, but I still don't get it. Thank you

function frankenSplice(arr1, arr2, n) {
    return arr2.splice(n,0,arr1);
}

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

Upvotes: 0

Views: 850

Answers (4)

user9165261
user9165261

Reputation:

Splice doesnt 'equal' the result, it directly writes it back to the variable. So instead of returning arr2.splice(n, 0, arr1); you have to write arr2.splice(n, 0, arr1); return arr2

Upvotes: 0

jshamble
jshamble

Reputation: 491

splice is used for concatenating singular elements to an array.

If you want to combine arrays, first splice the element to one array:

var arr1 = [1,2,3,4]; // elements could be anything, I am just using integers here.
arr1.splice(n,0,element);

Then use concat if you want to combine two arrays.

var arr1 = [1,2,3,4];
var arr2 = [5,6,7,8];
var result = arr1.concat(arr2);

Upvotes: 1

Sasha Kondrashov
Sasha Kondrashov

Reputation: 4580

The question you are asking might not be the question you want answered, but from the MDN:

Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

You are expecting your function to return the spliced array, for which you need:

function frankenSplice(arr1, arr2, n) {
    arr2.splice(n,0,arr1);
    return arr2;
}

However, I suspect that @jshamble is right and you are not actually looking to use .splice().

Upvotes: 0

isp-zax
isp-zax

Reputation: 3883

As correctly mentioned above, splice is usually used for adding single elements. Nothing, however, prevents it from working with arrays and adding those as elements to the other arrays. The reason for returning an empty array is that it returns array of deleted elements, not new array.

If you want to return updated array, do

function frankenSplice(arr1, arr2, n) {
arr2.splice(n,0,arr1);
return arr2;
}

Upvotes: 1

Related Questions