0

I have a nested array in javascript. The top level has a numerical index, the second level arrays contains various data. I want to be able to remove an element from the array using the top level index.

    var my_array = [];

    my_array[12] = ['cheese', 'egg', 'ham'];
    my_array[24] = ['balloon', 'frog'];
    my_array[33] = ['chicken', 'goose'];

How do I delete my_array[24]? I have tried using splice with $.inArray but inArray returned the index as -1. I don't want to use indexOf because of it's browser limitations - also I think it will give me the same problem as inArray.

Thanks!

4
  • Your explanation is awkward to me...could you just show exactly the array you have and the array you need? Commented Nov 17, 2013 at 18:26
  • 1
    If I understand correctly: delete my_array[24]; Commented Nov 17, 2013 at 18:27
  • @adeneo delete won't affect the length. But, the property/index will be removed/undefined. Commented Nov 17, 2013 at 18:33
  • @JonathanLonowski - in this particular case the length will be 34, as that's how many indices there really are. Commented Nov 17, 2013 at 18:37

3 Answers 3

1

my_array.splice(24, 1); will remove the item at index = 24.

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

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

Comments

1

Create a function:

function deleteByIndex(arr, index) {
    var new_arr = [];
    for (var i=0; i<arr.length; i++) {
        if (arr[i] && i!=index) {
            new_arr[i] = arr[i];
        }
    }
    return new_arr;
}

FIDDLE

call it like var new_array = deleteByIndex(my_array, 24);

1 Comment

Your method works, but is more complicated than the one I have marked as the correct answer.
1

If want to remove frog from main array index 24 by it's known index of 1

myArray[24].splice(1,1);

If want to search for frog anywhere and remove parent.

var term='frog';
my_array=$.grep(my_array,function(element,i){
     return $.inArray( term, element) !=-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.