I have an array like var aa = ["a","b","c","d","e","f","g","h","i","j","k","l"];
I wanted to remove element which is place on even index. so ouput will be line aa = ["a","c","e","g","i","k"];
I tried in this way
for (var i = 0; aa.length; i = i++) {
if(i%2 == 0){
aa.splice(i,0);
}
};
But it is not working.
filter method. var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var output = arr. filter(function(item) { return item % 2 === 0; }); Output will be a new array of the filtered values (Only even).
How can I iterate over my list and cleanly remove those odd-indexed elements? Fun fact: to remove all even (positioned) elements you can do: for x in lst: lst. remove(x) . To remove all odds do: iter_lst = iter(lst); next(iter_lst); for x in iter_lst: lst.
You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove. The splice method can accept many arguments.
Use Array#filter
method
var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];
var res = aa.filter(function(v, i) {
// check the index is odd
return i % 2 == 0;
});
console.log(res);
If you want to update existing array then do it like.
var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"],
// variable for storing delete count
dCount = 0,
// store array length
len = aa.length;
for (var i = 0; i < len; i++) {
// check index is odd
if (i % 2 == 1) {
// remove element based on actual array position
// with use of delete count
aa.splice(i - dCount, 1);
// increment delete count
// you combine the 2 lines as `aa.splice(i - dCount++, 1);`
dCount++;
}
}
console.log(aa);
Another way to iterate for loop in reverse order( from last element to first ).
var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];
// iterate from last element to first
for (var i = aa.length - 1; i >= 0; i--) {
// remove element if index is odd
if (i % 2 == 1)
aa.splice(i, 1);
}
console.log(aa);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With