1
var arr = [["test","1"],["demo","2"]];

// $.inArray() ???
// .splice() ???
// $.each() ???

$("code").html(JSON.stringify(arr));

If I will find matching array by "test" (unique) keyword , I will remove ["test","1"]

So arr after removed will be [["demo","2"]]

How can I do that ?

Playground : http://jsbin.com/ojoxuy/1/edit

5 Answers 5

2

This is what filter is for:

newArr = arr.filter(function(item) { return item[0] != "test" })

if you want to modify an existing array instead of creating a new one, just assign it back:

arr = arr.filter(function(item) { return item[0] != "test" })

Modificator methods like splice make code harder to read and debug.

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

1 Comment

Great solution, but mind the requirement ECMAScript 5th Edition. And technically it always creates a new array.
1

You could do something like this:

function remove(oldArray, itemName) {
    var new_array = [];

    for(var i = 0, len = oldArray.length; i < len; i++) {
        var arr = oldArray[i];

        if (arr[0] != itemName) new_array.push(arr);
    }

    return new_array;
}

And call it like this:

var arr = [["test","1"],["demo","2"]];
var new_arr = remove(arr,'test');

I'm making assumptions here and not doing any real error checking but you get the idea.

2 Comments

Can I use remove from arr , not make a new array ? , Thanks anyway
No not without altering the Array object. Check out Jorge's answer, splice() might be the better solution.
1

Perhaps something like:

for(var i = 0; i < arr.length; i++) {
  if(arr[i][0] == "test") {
   arr.splice(i, 1);
   break;
  }
}

3 Comments

I forgot about splice() :)
im so sorry but @thg435 is better answer :( , thanks anyway :D
@l2aelba Sure no worries. I agree filter seems more straightforward. Do note zeroflagL's comment on that answer though.
0
var arr = [["test","1"],["demo","2"]];

function checkArrayElements(a, index, arr) {
  if(a[0]=="test"){
    delete arr[index];
    arr.splice(index,index+1);
  }
}
arr.forEach(checkArrayElements);
$("code").html(JSON.stringify(arr));

NOTE: This removes any inner array in arr with the 0 element = "test"

Comments

0

Check this one

function rmEl(a,v)
{
for(var i=0;i<a.length;i++)
    {

      if(a[i][0]==v)
      {
        a.splice(i,i+1);
        i=-1;
      }
      $("code").html(JSON.stringify(a));       
    }
 return a;
} 

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.