JQUERY - remove array from a multidimensional array with key

2.5k views Asked by At

I am trying to remove an array in a multidimensional array if the id is the same off the given one.

var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}];

var result = test_arr.filter(function(v,i) {  
     if (v[0] === '123456'){ test_arr.splice(i,1) } 
}); 

//alert( test_arr[0].id)
alert(result)

http://jsfiddle.net/ofLg0vq5/2/

How Could I do this?

2

There are 2 answers

0
Nick Parsons On BEST ANSWER

The issue with your current solution is that you're not using .filter correctly. .filter expects its passed function to return a boolean. If true is returned, the current element will be kept in the newly generated array. If it is false, the current element will be omitted. So, instead of trying to remove the element from test_arr using .splice, use .filter to decide what stays and what gets removed.

Also, note that in your example v is referring to a given element (a particular object) in your test_array. Thus, you do not need to target index 0 of your object, but rather you need to get the id of the current object.

var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}];

test_arr = test_arr.filter(function(elem) {  
  return elem.id !== '123456'; 
}); 

console.log(test_arr); // [{"name": "ggg", "city": "uk", "id": "777456"}]

If you want a "cleaner" solution you can use an arrow function with destructing assignment:

test_arr = test_arr.filter(({id}) => id !== '123456'); // [{"name": "ggg", "city": "uk", "id": "777456"}]

var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}];

test_arr = test_arr.filter(({id}) => id !== '123456'); // [{"name": "ggg", "city": "uk", "id": "777456"}]
console.log(test_arr);

0
Vatsal Shah On

@Nick had given solution without .splice, but If for any reason you still want to go for .splice solution, you can try below code.

You are were checking id in wrong way, in below solution it will remove all objects with id - 123456

http://jsfiddle.net/u0qshcvf/2/