0

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
  • 2
    var result = test_arr.filter(v => v.id !== '123456' ) Commented Jan 17, 2019 at 12:13
  • NB: this question has nothing to do with jQuery..., but JavaScript. Please update the tags. Commented Jan 17, 2019 at 12:14

2 Answers 2

3

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);

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

Comments

2

@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/

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.