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]
?
- use
splice
instead ofdelete
- 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
Post a Comment