Wednesday, 30 April 2014

Playing with splice to remove rows from the array

I am trying to learn more about the Javascript funciton "splice"
http://www.w3schools.com/jsref/jsref_splice.asp

Example 1:
simple one dimensional array:
var numbers = [1,2,3,4]

numbers.splice(2,1); // removes third item in the array.

New array is: 1,2,4


var numbers = [[1,2,3,4],[10,20,30,40]];

numbers.splice(1); // removes a whole row of the data from the two dimensional array

New array is 1,2,3,4

HOWEVER, this will also delete everything after 1 in a multidimensional array. Not sure why...


Documentation here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice


It says:
"If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed."

So here is what I have to do:
var numbers = [[1,2,3,4],[10,20,30,40], [100, 200, 300, 400]];
var splicedNumbers = [[1,2,3,4],[10,20,30,40], [100, 200, 300, 400]];
    document.write("<br>");
    document.write("<br>");
document.write(numbers);

splicedNumbers.splice(1,1); // this now removes just the second row in the array!

    document.write("<br>");
    document.write("<br>");
document.write(numbers);
    document.write("<br>");
    document.write("<br>");

document.write(splicedNumbers);

Output:
1,2,3,4,10,20,30,40,100,200,300,400

1,2,3,4,10,20,30,40,100,200,300,400

1,2,3,4,100,200,300,400






No comments:

Post a Comment