Reputation:
I need one help. I need to delete row from an array as per some condition using JavaScript. I am explaining my code below:
var arr = [{
'value': '',
'name': 'Rajeev'
}, {
'value': '1',
'name': 'Raj'
}, {
'value': '',
'name': 'Ram'
}];
for(var i=0;i<arr.length;i++){
if(arr[i]['value']==''){
arr.splice(i,1);
}
}
Here after any value is deleting the array index is changing so it can not be deleted properly at every condition. I need to delete the row whose value ==''
. Please help me.
Upvotes: 0
Views: 1516
Reputation: 41
using lodash you can filter it out easily
the first parameter will be your array and the function returns value without ''
var fArray = _.remove(arr, function(obj) {
return ( obj.value != '' ); });
fArray will be your desired array with value not ''
Upvotes: 0
Reputation: 2571
You are changing the size of the array but keep increasing the index, if you want to change array size while running a loop a suggest you use
for each (var item in arr) {
if(item.val==''){
arr.splice(item ,1);
i--;
}
of you can do it in a more efficient way like this
array = arr.filter(function(currentChar) {
return currentChar !== " ";
});
Upvotes: 0
Reputation: 912
How about creating a new array, adding the items that are not '' and replacing the old with new ? Replace your loop with code below and see if it works.
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i]['value'] !== '') {
newArr.push(arr[i]);
}
}
arr = newArr;
Fiddle: https://jsfiddle.net/sno3pphs/
Upvotes: 0
Reputation: 622
Wont work because the lenth of your array is dynamically changing when you remove an element. You have to decrease the i variable. Try:
var arr = [{
'value': '',
'name': 'Rajeev'
}, {
'value': '1',
'name': 'Raj'
}, {
'value': '',
'name': 'Ram'
}];
for(var i=0;i<arr.length;i++){
if(arr[i]['value']==''){
arr.splice(i,1);
i--;
}
}
Upvotes: 0
Reputation: 115242
It will skip elements since removing element will change the index, but you are not updating the value of i
. Do it in reverse order to avoid such problems, i.e, end to start.
var i = arr.length;
while(i--){
if(arr[i]['value']==''){
arr.splice(i,1);
}
}
Upvotes: 0
Reputation: 386680
You could iterate from the end, because Array#splice
reduces the length of the array.
In your code, and if you splice, you have to keep the index at the same index, without incrementing.
for (var i = arr.length - 1; i >= 0; i--){
if (arr[i]['value'] == '') {
arr.splice(i, 1);
}
}
Upvotes: 1