Deleting JavaScript array element shows undefined -


this question has answer here:

i have javascript array objects , array having ids. want compare objects in array array of ids , if id found in object, want remove element array. doing result shows undefined in place of deleted element.

var data = [{"name": "john_smith","val":"3","id":"2"},{"name": "peter_adams","val":"2","id":"3"},{"name": "priya_shetye","val":"1","id":"4"},{"name": "sara_brown","val":"4","id":"5"}] var arr = ["2","5"]; (var = 0; < data.length; i++) {     for(var j=0;j<arr.length;j++){         if (arr[j]==data[i].id ) {             delete data[i];         }     } } 

the result shows [undefined,object object,object object,undefined]. there way [object object,object object]?

  1. use splice instead of delete
  2. loop array length-1 0, otherwise you'll miss deal data.
var data = [{"name": "john_smith","val":"3","id":"2"},{"name": "peter_adams","val":"2","id":"3"},{"name": "priya_shetye","val":"1","id":"4"},{"name": "sara_brown","val":"4","id":"5"}]; var arr = ["2","5"]; (var = data.length-1; >= 0; i--) {       for(var j = 0;j < arr.length;j++){           if (arr[j]==data[i].id ) {               data.splice(i,1);         }     } } console.log(data); 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -