1

Here is my array:

var myarray = [["d1", "sections/Dashboard-summary.html", "Dashboard"], 
               ["add", null, ""],
               ["20", "sections/MW-1-summary.html", "MW-1"],
               ["21", "sections/SB-5-summary.html", "SB-5"]]

How do I remove the second element ["add", null, ""] so that the new array is

[["d1", "sections/Dashboard-summary.html?781", "Dashboard"],
["20", "sections/MW-1-summary.html?903", "MW-1"],
["21", "sections/SB-5-summary.html?539", "SB-5"]]

That element might not always be in the second position but its first value will always be "add". How do I remove the array with the first value (myarray[1][0]) of "add"?

3
  • Does this need to be an array? For this kind of thing it would be better to use a linked list. Otherwise you'll have to write code to iterate through your array, find the entry, create a new array 1 size smaller, and copy all the information minus the "add". Commented Apr 21, 2011 at 1:33
  • @Tyler: this is JavaScript. Arrays are lists. Commented Apr 21, 2011 at 1:43
  • @Matt Yeah you're right. For some reason I completely forgot that fact. Good point. Commented Apr 21, 2011 at 3:42

3 Answers 3

4

That element might not always be in the second position but its first value will always be "add". How do I remove the array with the first value (myarray[1][0]) of "add"?

Use a loop with splice().

for (var i = 0, myarrayLength = myarray.length; i < myarrayLength; i++) {
    if (myarray[i][0] === 'add') {
        myarray.splice(i, 1);
        break;
    }
}

jsFiddle.

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

3 Comments

slice will return the part of the array that you deleted and will not modify the original array. Splice will actually remove the element from the array.
After commented on your response I realized I made the same mistake :S
Note this from the question: "That element might not always be in the second position"
0

Use splice, like so:

myarray.splice(1, 1)

See this tutorial for more information on splice.

4 Comments

Please avoid w3schools. MDC is a much better source for JavaScript reference, in this case see Array.splice().
Splice works when you know the position of the element to be removed. But in my case the empty element wont always be in the second position. How do I find the empty element and remove it?
You could iterate over the loop and see if typeof(myarray[i]) == "undefined".
@Matt Ball: Thanks for the link. I didn't know I was committing such an atrocity.
0

You can remove it completely (slow):

myarray.splice(1, 1);

You can delete it from the array, and left a "hole" in it (left the position 1 undefined):

delete myarray[1];

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.