How to splice an array out of a nested array - javascript

Afs35mm picture Afs35mm · Sep 1, 2015 · Viewed 9.1k times · Source

I am attempting to splice a nested array out of its parent array. Consider the following array. items.splice(0,1) should give me the first nested array([1,2]), however it seems to give me the first nested array, still nested inside of an array:

var items = [[1,2],[3,4],[5,6]];

var item = items.splice(0,1); // should slice first array out of items array

console.log(item); //should log [1,2], instead logs [[1,2]]

However it seems to return the needed array (first item), in another array. And I'm not able to get the full array unless I do item[0]. What in the world am I missing!?

Answer

MinusFour picture MinusFour · Sep 1, 2015

The MDN says Array.prototype.splice:

Returns

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.

So, it won't return just the deleted element, it will be wrapped in an array.