3

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!?

Afs35mm
  • 549
  • 2
  • 8
  • 21

5 Answers5

5

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.

Community
  • 1
  • 1
MinusFour
  • 13,913
  • 3
  • 30
  • 39
  • Kind of crazy I never knew that splice automatically places it inside a newly created array, I kind of just always assumed it worked that way because it was being taken from an already existing array. Thinking about it that makes sense because that's how Array.prototype.slice.call(arguments) works considering it's only an array-like object :) – Afs35mm Sep 01 '15 at 19:25
1

splice() changes the contents of an array, and returns an array with the deleted elements.

In your case, your original array has elements that also happen to be arrays. That might be confusing you.

cybersam
  • 63,203
  • 6
  • 53
  • 76
0

.splice() is returning correct array at item ; try selecting index 0 of returned array to return [1,2] ; to "flatten" item , try utilizing Array.prototype.concat() ; see How to flatten array in jQuery?

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

var item = items.splice(0,1); // should slice first array out of items array
// https://stackoverflow.com/a/7875193/
var arr = [].concat.apply([], item);

console.log(item[0], arr);
Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177
-1

To replace a two dimensional array you should use array[row][col] for example

for(var row = 0; row < numbers.length; row++) {
    for(var col = 0; col < numbers[row].length; col++) {
        if (numbers[row][col] % 2 === 0) {
            numbers[row][col] = "even";
        } else {
            numbers[row][col] = "odd";
        }  
    }

}
console.log(numbers);
Alicia Guzman
  • 49
  • 1
  • 4
-1

You should reference the first array in items, and then splice it. Try working snippet below.

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

var item = items[0].splice(0,2);

console.log(item);
M'Boulas
  • 133
  • 1
  • 2
  • 14