OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How do I extract elements with an even index of an Array?

  • Thread starter Thread starter DrStrangeLove
  • Start date Start date
D

DrStrangeLove

Guest
Code:
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?

<pre><code>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));
</code></pre>

<p><a href="http://jsbin.com/unocar/2/edit" rel="noreferrer">http://jsbin.com/unocar/2/edit</a></p>

<p>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?</p>
 

Latest posts

Top