Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all the odd indexes (eg: a[1],a[3]..) value from the array

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.

like image 885
shanky singh Avatar asked Aug 08 '16 11:08

shanky singh


People also ask

How do you remove odd numbers from an array?

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 do you get rid of odd indexed elements in a list?

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.

How do you remove indices from an array?

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.


1 Answers

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);
like image 159
Pranav C Balan Avatar answered Oct 19 '22 23:10

Pranav C Balan