How to remove all the odd indexes (eg: a[1],a[3]..) value from the array
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);
you can remove all the alternate indexes by doing this
var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];
for (var i = 0; i < aa.length; i++) {
aa.splice(i + 1, 1);
}
console.log(aa);
or if you want to store in a different array you can do like this.
var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];
var x = [];
for (var i = 0; i < aa.length; i = i + 2) {
x.push(aa[i]);
}
console.log(x);
You can use .filter()
aa = aa.filter((value, index) => !(index%2));