What is the proper way to retrieve items from an Array that have an index that is evenly divisible by

let numbers = [4, 5, 7, 8, 14, 45, 76];

function getEvenElements(arr) {
  let evenArray = [];

  for (let i = 0; i < arr.length / 2; i++) {
    evenArray.push(arr[2 * i]);
  }

  return evenArray.filter(num => num !== undefined);
}

alert(getEvenElements(numbers));

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

I attempted to extract only the even-indexed elements from an array using this code. It seems to be working, but it includes empty values as well. How can I modify the code to output existing elements only?

Answer №1

To extract every second element from an array, you have two options:

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

Another approach is to increment i by 2 in each iteration to skip every other element:

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

Note: Be cautious as the provided code retrieves elements with odd indexes instead of even ones. To address this, use i % 2 === 1 or initialize i = 1 at the beginning of the loop.

Answer №2

To ensure compatibility with Internet Explorer 9 and above, you can utilize the Array.filter method.

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

If you need a fallback for older versions of Internet Explorer, the following code snippet can be added:

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp */) // Fallback for IE
  {
    "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;
  };
}

Answer №3

Make this code work for the year 2018 :)

Extract the elements at odd indexes by using filter method

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

Answer №4

Although this question may be considered old, I want to share a one-liner filter tip:
For odd numbers: arr.filter((e,i)=>i%2)
For even numbers: arr.filter((e,i)=>i%2-1)
A more conventional approach for finding even numbers: arr.filter((e,i)=>!(i%2))

It is unnecessary to use ===1 as suggested by sumit. Utilizing mod 2 already yields either 0 or 1, which can be treated as boolean values.

Instead of using i%2, you can opt for i&1, which may enhance performance on large arrays but is restricted to 31-bit integers.

Answer №5

Have you considered using the % operator? It calculates the remainder of a division.

Instead of the existing loop, you could implement:

if ((i % 2) === 0) {
    newArr.push(arr[i]);
}

Answer №6

let numbers = [2, 6, 8, 14, 23, 45, 67];

function getEvenNumbers(array) {
  let evenArray = [];

  for (let num in array) {
    if ((array[num] % 2) == 0)
      evenArray.push(array[num]);
  }

  return evenArray;
}

alert(getEvenNumbers(numbers));

Answer №7

It's important to note why the outcome may not match your expectations when iterating over an array of size N, even though others have found excellent solutions. When iterating over an array of size N and attempting to push elements into a new array, the resulting array will still have size N. However, if only half of the elements are present in the original array, then the remaining slots in the resulting array will be filled with blanks. By checking for conditions like a[2*i] existing or a[i] % 2 == 0 before inserting, the resulting array will contain only the values with even indexes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the depths of asynchronous calls in AngularJS with nested functions

Currently, I'm tackling a small project with AngularJS and finding myself tangled in multiple asynchronous calls that are starting to become chaotic. I know there must be a more efficient way to handle these calls, but I'm unsure of the best appr ...

Enhancing performance by implementing cache mechanism for storing search results in a table with multiple filtering options using Vue

In my current project, I am utilizing VueJS. However, the issue I am facing is not necessarily exclusive to this framework - but if there is a vue-specific solution available, that would be my preference. The task at hand involves constructing a table wit ...

Adjust the column count in mat-grid-list upon the initial loading of the component

My goal is to implement a mat-grid-list of images with a dynamic number of columns based on the screen size. Everything works perfectly except for one small glitch – when the grid first loads, it defaults to 3 columns regardless of the screen size until ...

Nested loop with built-in delay

Currently, I am attempting to modify a loop that adjusts the value of multiple input variables: $("#wrap input").each(function( index ) { for( i = 10 ; i > 0 ; i--) { $(this).val(i); console.log( index + ": " + $(this).val() ); } }); <script src ...

The componentWillUnmount method is not being called

I'm currently working on a Backbone application and I'm in the process of integrating React components. The React component is being mounted using the following code: ReactDOM.render( <WrappedComponent />, node ); where "node" represents ...

Calculating the number of days left within a month using dayjs

Currently, I'm facing a challenge that seems to have no easy online solution, and if there's one thing I find particularly frustrating; it's dealing with dates. My current task involves calculating a person's age in months and days. Fo ...

What is the process for disabling the CSS module feature in Next.js?

In Next.js, Global CSS can only be imported in _App.js. However, importing global CSS in every component is not allowed, so we have to use CSS modules to comply with this restriction imposed by Next.js. Currently, I am in the process of migrating a large ...

Issue with Angular directive failing to update object within ng-repeat loop

I am working on a directive that is responsible for displaying a tree of folders, including the ability to show subfolders. The directive uses recursion to handle the display of subfolders. <div ng-click="toggleOpen()" class="action"> <span ...

Tips for creating multiple functions within a single JavaScript function

Is there a way to combine these two similar functions into one in order to compress the JavaScript code? They both serve the same purpose but target different CSS classes. The goal is to highlight different images when hovering over specific list items - ...

Tree structure implementing polymorphic relation within a multidimensional array

In order to achieve my goal, here's a straightforward explanation: I aim to create templates. Each "Template" consists of a "Panel". This "Panel" contains some "Item" and another "Panel". We need to follow this process step by step until we reach the ...

Determine the maximum value in an array using recursive Java function

Can someone assist me with using recursion to find the largest number in an array? I am currently not achieving the desired results and any guidance would be greatly appreciated. public class ArrayMax { public static int largestNumber(int[] array) { ...

Determining the best use-case for a React framework like Next or Gatsby versus opting for Create React App

As I delve into the world of React and JavaScript, I find myself in the fast-paced prototyping stage. I can't help but ponder at what point developers choose to utilize frameworks like Next.js or Gatsby.js over the usual Create React App. I'm pa ...

Can someone show me how to make an ajax request from a panel within a Firefox extension?

Seeking guidance on utilizing panels in the Firefox addon. How can I initiate an ajax request from a panel? Also, what is the best way to debug a panel since Firebug does not seem to recognize it? ...

"Fixing the Vertical Order of Divs with Jquery: A Step-by-

Before I completely lose my mind, I need some help with a coding issue. Right now, I have two initial divs displayed. The user should be able to add these divs below the original ones as many times as they want, or remove them if needed. I've been att ...

Seeking materials for WebDriverJs?

It has come to my attention that there are some valuable resources available: http://docs.seleniumhq.org/docs/03_webdriver.jsp https://code.google.com/p/selenium/wiki/WebDriverJs However, I am curious if there exists a comprehensive website that prese ...

Anticipated the server's HTML to have a corresponding "a" tag within it

Recently encountering an error in my React and Next.js code, but struggling to pinpoint its origin. Expected server HTML to contain a matching "a" element within the component stack. "a" "p" "a" I suspect it may be originating from this section of my c ...

What type of data structure does TCL utilize for its array implementation?

As I'm tackling the challenge of manipulating large dates in TCL, I can't help but wonder about the speed of searching in arrays. It seems that the process of filling up arrays is not as efficient compared to other popular scripting languages. ...

What is the reason behind the limitation of adding no more than 1048576 elements at once with array_pad?

According to the documentation for array_pad, it states that The maximum number of elements that can be added at once is 1048576. I attempted to research the origin of this limit but could not find any information. The only related questions were about ...

Enhance Page Content Dynamically with Symfony2 and Ajax-Like Functionality

When assessing an ArrayCollection in my Template, I am currently using the following loop: {% for article in articles %} <li {% if article.new %} class="new" {% endif %} >{{ article.name|e }}</li> {% endfor %} My go ...

Transferring my JavaScript variable to PHP through Ajax

I'm currently facing an issue where my JavaScript variable is not being successfully passed to a PHP variable using AJAX in order to update my SQL database. The function is being called, but for some reason the data is not being sent to PHP.php. UPDA ...