How do I extract even elements of an Array?
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);
Even if this question is quite old, I would like to add a one-liner filter:
Odd numbers: arr.filter((e,i)=>i%2)
Even numbers: arr.filter((e,i)=>i%2-1)
A more 'legal' way for even numbers: arr.filter((e,i)=>!(i%2))
There's no need to check with ===1
like sumit said. mod 2
already returns a 0 or a 1, you can let them be interpreted as boolean values.
You can use i&1
instead of i%2
, while it benefits performance on big arrays, it can work only on 31 bit integers.
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;
};
}