i am facing this issue of splicing an array.i checked out all the examples i could find but all in vein. the troubles are these nested if conditions inside the for loop.i am doing i-- but not able to go ahead. can anybody help me out and explain the approach.i am adding a snippet. the prob is that, whenever i don't do the i-- operation, and splice the array, alternate removal of elements happens but upon adding the i--, i am not able to proceed any further. i tried --i, but now i am confused as to what i am doing wrong. here m is an array of number from 1 to 20 serially. having length 20.
var k=13;
for (var i = 0; i < m.length; i++) {
if (m[i] < k) {
if (i != 0 && i != m.length) {
m.splice(i, 1);
}
if (i == 0) {
m.splice(i, 1);
}
i--;
}
}
From what I can read, you want to filter
out all elements lesser than 13. You can do the same by using filter()
in javascript
const filterLimit = 13;
// Here filteredList is the list of all elements lesser than filterLimit
const filteredList = m.filter(item => item >= filterLimit);
Example:
const filterLimit = 13; const unFilteredList = [1, 13, 14, 2, 5, 33]; const filteredList = unFilteredList.filter(item => item >= filterLimit); console.log(filteredList);
There is an error in this approach and that's you must not change the parameter (i)
of the loop inside the loop
You can use while
instead:
var k=13;
var i=0;
while (i < m.length){
if(m[i] < k){
m.splice(i, 1);
}else{
i++;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.