Is there a way to have the even numbers in an array printed before the odd numbers?

Looking for a way to separate even and odd numbers into two arrays? This function will do just that, but with a twist - the evens array will be printed before the odds.

var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];

function customDivider(numbersArray) {
  var evensOdds = [[], []];
    for (var i = 0; i < numbersArray.length; i++) {
      evensOdds[i & 1].push(numbersArray[i]);
  }
  return evensOdds;
}

Answer №1

If you're looking to categorize numbers based on their even and odd values, instead of relying solely on the index (id), consider using the value itself - numbersArray[i] % 2.

const numbersArray = [1, 2, 34, 54, 55, 34, 32, 11, 19, 17, 54, 66, 13];

function segregator(numbersArray) {
  const evensOdds = [[], []];
  for (let i = 0; i < numbersArray.length; i++) {
    evensOdds[numbersArray[i] % 2].push(numbersArray[i]);
  }
  return evensOdds;
}

console.log(segregator(numbersArray));

If you wish to divide them by even and odd indexes, use (i + 1) % 2 to identify the correct sub array:

const numbersArray = [1, 2, 34, 54, 55, 34, 32, 11, 19, 17, 54, 66, 13];

function segregator(numbersArray) {
  const evensOdds = [[], []];
  for (let i = 0; i < numbersArray.length; i++) {
    evensOdds[(i + 1) % 2].push(numbersArray[i]);
  }
  return evensOdds;
}

console.log(segregator(numbersArray));

Answer №2

Just for kicks, here's a forEach variation of the solution that was approved.

    let numsArr = [1,2,34,54,55,34,32,11,19,17,54,66,13];
    let even_odd = [ [], [] ];

    numsArr.forEach( num => even_odd[num % 2].push(num) );

    console.log(even_odd);

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

Run code after all images have been rendered in vuejs

Is there a way to execute code after all images have loaded, specifically needing to set the scroll in a specific position? Using nextTick() processes the code before the images are loaded. The mounted and created methods can't be used since the code ...

The compatibility issue between Rails 7 and Bootstrap 5.2.3, along with importmaps JavaScript, is causing dysfunction in the

Feeling a bit lost here, as I've tried several solutions from Stack Overflow related to getting bootstrap 5.2.3 javascript to work for a dropdown menu. Importmaps seem like the best approach, although esbuild was attempted with no luck. Below is a sn ...

Generating dynamic JSON objects in Node.js

Here is the initial JSON data I have: { "fullName": "abc", "age": 19, ... } I am looking to utilize Node.js in order to add elements from the above JSON to an object called Variables within the following JSON: { &q ...

Selenium Driver Automated Text Box Completion

Struggling with creating a registration process on a website? Take a look at the script I've been using: package agent; import java.util.regex.Pattern; import java.awt.List; import java.util.concurrent.TimeUnit; import org.junit. ...

What is the process for renaming a Discord channel through nodeJS and discordJS?

I'm currently developing my first Discord bot using node.js and discord.js. My objective is to provide real-time information about a Minecraft server through Discord. What I aim to achieve is to have a channel that automatically updates its name per ...

Two functions that require multiple clicks to execute

My JavaScript code requires two consecutive clicks to function properly for some reason. Here is the code for the link: <a href="" onclick="select_all_com(); return false">Select All</a> Now, here is the code for the function that is called w ...

Modifying the embed to shift colors over a specified duration in discord.js

case 'test': let time = "10s" const testEmbed = new Discord.RichEmbed() .setTitle("Testing") .setColor('#000000') message.channel.send(testEmbed); setTimeout(function(){ testEmbed.setColo ...

Guide on exporting member formModule in angular

After compiling my code in cmd, an error message is displayed: ERROR in src/app/app.module.ts(3,10): error TS2305: Module '"C:/Users/Amir_JKO/my-first-app/node_modules/@angular/forms/forms"' does not have an exported member 'formModul ...

How can I fetch data from another table by querying array values in Postgresql?

I have recently started working with a database that includes an array field (Phones) containing IDs from another table. I am new to this feature and I am wondering how I can retrieve all the records from the Public_Phone table that are associated with the ...

Animating CSS using JavaScript

Recently diving into the world of JavaScript, I've taken on the challenge of creating an analog clock. I began by crafting the second hand using CSS but now I'm eager to transition it to Javascript without relying on jQuery or any other JS framew ...

Choose a phrase that commences with the term "javascript"

I need assistance in creating two unique regular expressions for the following purposes: To select lines that begin with 'religion'. Unfortunately, my attempt with /^religion/g did not yield any results. To match dates and their correspondi ...

Exploring cross-browser compatibility with the use of CSS3 and JavaScript

Starting a new project to create a fresh website. It seems like many people are leaning towards CSS3 and AJAX, neglecting browsers without JavaScript support. They resort to workarounds like enabling CSS3 through JavaScript in older browsers. Is this the ...

Ways to dynamically incorporate input fields into a form

My current project involves managing an Asset Management system for a company with multiple locations. This system has the capability to return unused asset items back to storage. I am faced with the task of returning a large number of items, which requi ...

Is it possible to retrieve the parent object?

My code snippet is as follows, and I'm struggling to access the data object from within the innerFn function. Is there a way to accomplish this? export default { data: { a: "a", b: "b" }, fn: { innerFn: () => co ...

Issue with Color in Line Chart of Flot Version 0.8.2

While working on Flot line charts and customizing their colors, I came across a strange issue. Once I set the first 3 colors, the plot started using the last color for all the remaining lines. This behavior was unexpected and not the norm. What adds to th ...

Trouble reading property 'map' in a react-redux todo application

Greetings! I am currently in the process of developing a to-do list application, but I have encountered the following error: TypeError: Cannot read property 'map' of undefined Below is the code snippet where the error occurs: 4 | function T ...

How do I include an icon on the far left of my NavBar menu? I'm having trouble figuring out how to add an icon to the header NavBar

How can I add an icon to the left of my NavBar header? I am struggling with adding an icon on the far left side of my NavBar. The NavBar is a custom class from NavBar.js. I want to include an icon in this bar on the leftmost side. I have already added b ...

Encountering an issue with Angular build in Docker: [ERR_STREAM_DESTROYED] - Write function cannot be called after a stream

Below is the docker file I'm using to build my Angular project: FROM node:12-buster-slim as build-step RUN mkdir -p /app COPY . /app WORKDIR /app RUN chmod 777 -R /app RUN npm install ARG configuration=production RUN npm run build -- --output-path=./ ...

Change the runat attribute in JavaScript to execute on the server side

Is there a way to dynamically set the runat attribute using client-side JavaScript? I am facing the challenge of adding rows to a table after the page is loaded and must ensure that their cell data is accessible on the server side. While I am open to marki ...

Running a Python Selenium script

I need some help executing this script using selenium. <div class="vbseo_liked"> <a href="http://www.jamiiforums.com/member.php?u=8355" rel="nofollow">Nyaralego</a> , <a href="http://www.jamiiforums.com/member.php?u=8870" rel="nofollo ...