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

Provide Arguments to a Function in Express JS

How's everything going? I'm curious to find out the best way, and if it's possible to send a specific parameter to an express function in NodeJS. I want to pass the string ('admin') or any other string that I choose to the 'R ...

What is the best way to iterate over my JSON data using JavaScript in order to dynamically generate cards on my HTML page?

var data = [ { "name":"john", "description":"im 22", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c7d7e7f0c2b212d2520622f">[email protected]</a>" }, { "name":"jessie", ...

Passing a global variable as an argument to a jQuery function is not allowed

I am attempting to display local weather information using an API. The API URL is generated based on the user's current position. var lat, lon = null; var key = "mykey"; var api = ""; function setApi(position){ lat = Math.round(position.coords.lati ...

What is the best way to identify the differences between two non-unique arrays in JavaScript? I initially relied on underscore, but I am willing to

Given two arrays: firstArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}, {id:'id3'}] secondArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}] The expected output is [{id:'id3'}] This ...

Keeping track of the toggle state using a cookie

While searching for a way to retain the toggle state, I stumbled upon js-cookie on GitHub. The documentation provides instructions on creating, reading, and deleting a cookie. However, an example would have been really helpful in enhancing my understanding ...

What is the best way to link the :style attribute with object syntax and incorporate multiple background images?

I'm experiencing an issue trying to bind CSS style with the object syntax to an image. The style object includes the CSS property background which refers to multiple background images, but unfortunately, these images are not showing up. Template < ...

PubNub's integration of WebRTC technology allows for seamless video streaming capabilities

I've been exploring the WebRTC sdk by PubNub and so far, everything has been smooth sailing. However, I'm facing a challenge when it comes to displaying video from a client on my screen. Following their documentation and tutorials, I have writte ...

What is the best way to manage various versions of JS libraries across different branches?

As a novice developer, I dabble in creating applications for personal use. My go-to tools are the Quasar framework for the front end and Python for the back end. I maintain a git repository where the master branch houses my "production code," but now I am ...

What method is most effective for combining two JSON files in Angular?

My data includes a json file with a product list that looks like this: [{"id":76, "name":"A", "description":"abc", "price":199, "imageUrl":"image.jpg", "productCategory":[{ "categoryId":5, "category":null },{ "categoryId":6, " ...

I can't seem to get anything to show up on my React

After starting to work with routing on react.JS, I encountered a challenge where the simple products.jsx file is supposed to display a simple message upon clicking, but it's not showing anything. Here is the code from Index.JS import React from &apos ...

jQuery: What's the Difference Between Triggering a Click and Calling a Function?

Imagine having certain actions assigned to a link using .click or .live, and wanting to repeat the same action later without duplicating code. What would be the right approach and why? Option 1: $('#link').click(function(){ //do stuff }); //c ...

Elegant Bootstrap 4 Carousel featuring a glimpse of the upcoming slide alongside the primary carousel item

I am in search of a straightforward Bootstrap 4 carousel that showcases a glimpse of the next slide on the right. Despite exploring similar questions, I have not found a suitable solution. The links to those questions are: 1)Bootstrap carousel reveal part ...

Having difficulty maintaining trailing zeroes in decimals after converting to float in Angular

I need assistance with converting a string to float in Angular. Whenever I use parseFloat, it seems to remove the zeros from the decimal values. How can I ensure that these zeros are retained with the numerical values? The example below should provide more ...

Vuetify's paginated server-side datatable does not support client-side sorting

The Challenge The issue I am facing revolves around using a server-side paginated datatable. Specifically, when utilizing the Vuetify data tables component and attempting to perform client-side sorting due to using a public API that I did not develop, the ...

developing a custom modal using a button in a React project with Material UI

Hello everyone, I have a question regarding React. I am fairly new to React and need some assistance with adding a new function that creates a Modal. I want to call this function onClick when the add icon is pressed (line 43). Any help would be appreciated ...

How does handleChange receive the value as an input?

Greetings! Currently, I am delving into the world of React and JavaScript. I am experimenting with a Table Component demo that can be found at the following link: https://codesandbox.io/s/hier2?file=/demo.js:5301-5317 In the demo, there is a function defi ...

Creating a cascade of falling balls with a single click: Here's how!

I'm currently working on a project where I have a ball dropping from the cursor location and redropping when the cursor moves to another position. However, I want to be able to create a new ball every time I click the mouse. I attempted the following ...

Create a function that triggers a fade-out effect on one button when another button is clicked

Hello everyone! I'm still getting the hang of things around here so please be kind. I need some assistance with my weather app project. Specifically, I've created two buttons and I want to make it so that when one is clicked, the other fades to g ...

Viewing a PDF within a MUI tooltip

Currently, I am facing an issue where I am attempting to show a preview of a PDF file inside a Material-UI (MUI) Tooltip when a user hovers over a MUI ListItem. While I have successfully displayed previews of PNG and JPG files using Next.js' Image com ...

Tips on modifying the maxlength attributes for all "field answer" class elements

Looking for some help with adjusting the "maxlength" attribute in a class called "field answer." The current maxlength is set to 250, but I need it changed to 9999. Can someone guide me through this process? <div class="field answer"> &l ...