How do I extract even elements of an Array?

var arr = [4, 5, 7, 8, 14, 45, 76];

function even(a) {
  var ar = [];

  for (var i = 0; i < a.length; i++) {
    ar.push(a[2 * i + 1]);
  }

  return ar;
}

alert(even(arr));

http://jsbin.com/unocar/2/edit

I have tried this code in order to output even (index) elements of an array. It works, but it also outputs some empty elements. How do I fix this code to output only existing elements?


Either use modulus:

for (var i = 0; i < a.length; i++) {
    if(i % 2 === 0) { // index is even
        ar.push(a[i]);
    }
}

or skip every second element by incrementing i accordingly:

for(var i = 0; i < a.length; i += 2) {  // take every second element
    ar.push(a[i]);
}

Notice: Your code actually takes the elements with odd indexes from the array. If this is what you want you have to use i % 2 === 1 or start the loop with var i = 1 respectively.


For IE9+ use Array.filter

var arr = [4,5,7,8,14,45,76];
var filtered = arr.filter(function(element, index, array) {
  return (index % 2 === 0);
});

With a fallback for older IEs, all the other browsers are OK without this fallback

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

This will work on 2018 :)

take the odd indexes and apply to filter

var arr = [4, 5, 7, 8, 14, 45, 76,5];
let filtered=arr.filter((a,i)=>i%2===1);
console.log(filtered);