开发者

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开发者_如何学Go 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);


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.


why don't you try with the % operator. It gives you the remaining of a division.

replace the loop block with

if ((i % 2) === 0) {
    ar.push(a[i])
}


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

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

  for (x in a)
  {

    if((a[x]%2)==0)
    ar.push(a[x]);  

  }
return ar;
}

alert(even(arr));


I just wanted to explain why your result is not what you expected since everyone else shows excellent solutions. You are iterating over an array size N so your resulting array will attempt to push elements in an array that will result in size N. Since only N/2 will be found in the original array your resulting array will fill the rest with blanks to fill in the rest of N. So if you checked to see if a[2*i] exists OR checked to see if a[i] % 2 == 0 before inserting, your resulting array will contain only the even indexed values


You need to test the elements for evenness like this:

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

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

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

  }

return ar;
}

alert(even(arr));

%2 is the modulo operator, it returns the remainder of integer division.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜