divide an array into two separate arrays depending on whether the index position is odd or even

Here is an example array: Arr1 = [1,1,2,2,3,8,4,6].

I'm trying to divide this array into two new arrays based on the odd or even position of elements. Can anyone provide a solution?

New Array 1 (odd positions): [1,2,3,4]
New Array 2 (even positions): [1,2,8,6]

Answer №1

nums = list.select (n) -> n % 7 == 0
otherNums = list.filter (n) -> n % 7 != 0

In a more stylistic CoffeeScript approach:

nums = (n for n in list if n % 7 == 0)
otherNums = (n for n in list when n % 7 != 0)

Answer №2

If you're looking for a solution, you might want to consider the following approach:

var Array1 = [1,1,2,2,3,8,4,6],
    Array2 = [],
    Array3 = [];

for (var index=0;index<Array1.length;index++){
    if ((index+2)%2==0) {
        Array3.push(Array1[index]);
    }
    else {
        Array2.push(Array1[index]);
    }
}

console.log(Array2);

Check out this JS Fiddle demo.

Answer №3

To make things simpler, consider using nested arrays:

finalResult = [ [], [] ]

for (let j = 0; j < inputArray.length; j++)
    finalResult[j & 1].push(inputArray[j])

If your audience mainly consists of users with modern browsers, you could swap the loop for forEach:

inputArray.forEach(function(value, index) { 
    finalResult[index & 1].push(value)
})

Answer №4

Implementing a practical method utilizing underscore:

numbers = [1, 1, 2, 2, 3, 8, 4, 6]
split = _(numbers).groupBy((num, index) -> index % 2 == 0)
[numbers1, numbers2] = [split[true], split[false]]

[edit] An updated solution is available using _.partition:

[numbers1, numbers2] = _(numbers).partition((num, index) -> index % 2 == 0)

Answer №5

let numbers = [1, 1, 2, 2, 3, 8, 4, 6]
let evenNumbers = []; 
let oddNumbers = []

let index;
for (index = 0; index <= numbers.length; index = index + 2) {
    if (numbers[index] !== undefined) {
        evenNumbers.push(numbers[index]);
        oddNumbers.push(numbers[index + 1]);
    }
}
console.log(evenNumbers, oddNumbers)

Answer №6

An idea would be to create two separate for loops that increase by 2 each time. In the initial loop, you could begin at 0, while in the subsequent loop, you could start at 1.

Answer №7

An alternative approach eliminating the need for modulo operator:

let evenArray = [];
let oddArray = [];
let index = 0;
let j;

for (j = 1; j < mainArray.length; j = j + 2){
    // Assign values to even and odd arrays based on index
    evenArray[index] = mainArray[j];
    oddArray[index] = mainArray[j - 1];
    index++;
}

// Handle last remaining number if array length is odd
if((j - 1) < mainArray.length){
    oddArray[index] = mainArray[j - 1];
}

Answer №8

Just for kicks, here is a little coffeescript snippet in two concise lines:

Numbers = [3,5,7,9,10,13]
[odd, even] = [a, b] = [[], []]
([b,a]=[a,b])[0].push num for num in Numbers

console.log odd, even
# [ 3, 5, 7, 9, 13 ] [ 10 ]

Answer №9

Here's a more concise version of tokland's proposed solution, utilizing underscore chaining function:

numbers = [8, 4, 21, 15, 10, 3, 6, 9]
_(numbers).chain().groupBy((num, index) -> index % 2 == 0).values().value()

Answer №10

CustomFilter is a unique Array method that allows users to input a collection of filter functions and receive an output containing arrays where the input and output are associated by keys within an object.


    Array.prototype.CustomFilter = function (filters) {
      let results = {};
      Object.keys(filters).forEach((key)=>{
         results[key] = this.filter(filters[key])   
      }); 
      return results;
    }
    //---- example : 
    
    console.log(
      [12,2,11,7,92,14,5,5,3,0].CustomFilter({
        odd:  (e) => (e%2),
        even: (e) => !(e%2)
      })
    )

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

If the Ajax request is successful, scroll to the bottom of a Div using jQuery

An interesting scenario arises with this Div that contains user messages, where the newest message always appears at the bottom of the Div and triggers a scroll bar if the message count exceeds the height of the div: <div class="list-group-message" s ...

Selecting list items using the up and down keys in JavaScript/jQuery

As the search terms dynamically populate a list of items, I am looking for a way to make the list items selectable/focused using the up/down keys and hide the dropdown with ESC key. <form> <div> <div class="field"> & ...

When I upgraded my "react-router-dom" from version "5.2.0" to "6.14.0", I encountered a warning stating "No routes matched location"

After updating react-router-dom from version "5.2.0" to "6.14.0", I encountered a warning saying "No routes matched location." Initially, I received an error stating that "<Route> is only meant to be used as a child of <Routes>, not rendered d ...

JavaScript allows for the manipulation of elements within a webpage, which includes accessing elements from one

There is a file that contains a fragment for the navbar. The idea is to have listItems in the navbar, and upon clicking on those listItems, another subnavigationbar should open below it. Below is the code I currently have: <!DOCTYPE html> <html x ...

KnockoutJS's data binding feature is failing to display any content within the table rows

My JavaScript function creates a model and applies it to an HTML document using knockoutJS. In the HTML file, I have two different ways of displaying the same data: 1- A select list (which is working fine) 2- A table (not showing the same data) I need a ...

Having trouble looping through an array of objects containing images in Javascript?

I am currently facing challenges with iterating through an array of objects that contain images. The array appears empty when logged in the console, but upon inspecting it in the console, I can see all the objects along with their iteration numbers. I have ...

Tips for selecting specific types from a list using generic types in TypeScript

Can anyone assist me in creating a function that retrieves all instances of a specified type from a list of candidates, each of which is derived from a shared parent class? For example, I attempted the following code: class A { p ...

Transfer the html div element to the ajax request

My server-side code runs multiple bigquery queries and organizes the results in a table. The client calls this code via an ajax request. I want to send the table/div generated by the server-side code to the client so that it can be rendered there. Is this ...

What is the best way to transition an absolute positioned element from right to center?

When hovering over an overlay element, I want the <h3> tag to appear with a transition effect from right to center, similar to the example shown here. Could someone please assist me in achieving this? Thank you in advance. HTML <div class="row m ...

JavaScript for Dynamic Scaling Animations

I am currently working on animating an SVG button and I am trying to incorporate the transform property with a fadeout using opacity attributes in Javascript. This is how I have attempted to write the code: (Starting with opacity 0 and scale 0) (I am awa ...

An ultimate guide to mapping a nested array in React.js

Problem: I am struggling to display the entire content of my array. The goal is to render all elements in the array, but so far I can only get one to show up. I have found that including [key] in the object fields is the only way to generate any output. ...

What is the process for extracting the time value from a jQuery timepicker?

I have been attempting to retrieve values from my time picker when a selection is made, but I am not seeing any values returned nor displayed in my HTML timepicker input field. Despite trying various methods, none have proven successful thus far. Method ...

IframeResizer.js is automatically readjusting its position to the top left corner (0,0) when a javascript event or

Within our internal web environment, I have implemented IframeResizer.js in a rather basic manner. The child page contains a table generated by a third-party application with mouseover/hidden and javascript tags associated with the TH elements (including a ...

Having trouble troubleshooting this issue where the object data is displaying in the console, but encountering an error when trying to use the resetValue

Index.html I am facing an issue while reading data from an object and the seek bar is giving a null error. The images and songs are stored locally, and I am trying to access them. <div class="music-player"> <div class="song&qu ...

Retrieve specialized information from a json file

I have a JSON variable called json which contains some data in JSON format. I am attempting to extract a specific portion of that data. One way to do this is by using the index as demonstrated below: var newdata = json[listid].Taxonomies[0]; However, my ...

Tips for concealing a collapsible navbar menu upon clicking elsewhere (Bootstrap 5)

I am trying to create a collapsible navbar menu: <div class="collapse navbar-collapse" id="navbarCollapsible"> .. menu items .. </div> My goal is to hide the menu whenever a user clicks outside of it (not just when click ...

Utilizing the split function within an ngIf statement in Angular

<div *ngIf="store[obj?.FundCode + obj?.PayWith].status == 'fail'">test</div> The method above is being utilized to combine two strings in order to map an array. It functions correctly, however, when attempting to incorporate the spli ...

How can I align Javascript output vertically in the middle?

I am currently facing an issue with a JavaScript clock displaying in a narrow frame: <!DOCTYPE html> <HTML> <HEAD> <TITLE>Untitled</TITLE> <SCRIPT> function checkTime(i) { if (i < 10) { ...

Is it really necessary to import React from 'react' in the index.js file when importing react is no longer required?

Currently diving into the world of React.js. I recently found out that after version 17, importing React is no longer necessary. My current React version is v18.2.0. Here's the code snippet in question: // import React from 'react'; import ...

What is the process for sending a request and obtaining a response from a REST API using JavaScript?

I have a private server set up on my computer with a built-in REST API. The base URL for the API is: . I am now looking to develop a client application for this server using the API. To authenticate on the server, the API endpoint is baseurl/login with the ...