Reputation: 448
I have an array I am trying to remove entry if a particular string is found The code is skipping an entry in the loop to check
unction test(){
var Concat_names = ["Test 1-Coms-2A Up", "Test 1-Included Units-10G", "test 2-Included Units-1000 Sa", "test 2-Percentage-MB"];
for (var i in Concat_names) {
console.log(Concat_names[i]);
var check_included_units = Concat_names[i].includes("Included Units");
console.log(check_included_units)
if (check_included_units == true) {
Concat_names.splice(i,1);
}
else if (check_included_units == false){
continue;
}
}
console.log(Concat_names);
}
The output is as below-
Please suggest what is wrong here and how to fix
Upvotes: 1
Views: 31
Reputation: 201378
In your script, when Concat_names.splice(i, 1)
is run, Concat_names
is changed. By this, i
is changed. I think that this might be the reason for your current issue. In this case, how about looping from the last element? When this is reflected in your showing script, how about the following modification?
var Concat_names = ["Test 1-Coms-2A Up", "Test 1-Included Units-10G", "test 2-Included Units-1000 Sa", "test 2-Percentage-MB"];
for (var i = Concat_names.length - 1; i >= 0; i--) { // I modified this line.
console.log(Concat_names[i]);
var check_included_units = Concat_names[i].includes("Included Units");
console.log(check_included_units)
if (check_included_units == true) {
Concat_names.splice(i, 1);
} else if (check_included_units == false) {
continue;
}
}
console.log(Concat_names); // [ 'Test 1-Coms-2A Up', 'test 2-Percentage-MB' ]
var Concat_names = ["Test 1-Coms-2A Up", "Test 1-Included Units-10G", "test 2-Included Units-1000 Sa", "test 2-Percentage-MB"];
var res = Concat_names.filter(e => !e.includes("Included Units"));
console.log(res)
Upvotes: 2