21

I have an array Arr1 = [1,1,2,2,3,8,4,6].

How can I split it into two arrays based on the odd/even-ness of element positions?

subArr1 = [1,2,3,4]
subArr2 = [1,2,8,6]
5
  • And please read the formatting FAQ; you've had almost a year to do so. Commented Nov 14, 2011 at 10:08
  • What's the point in this? I don't really get what your problem is or according to which criteria you want to split them. A few more infos would be great. Commented Nov 14, 2011 at 10:09
  • @Termi: It's pretty clear (albeit mostly from the title) Commented Nov 14, 2011 at 10:10
  • @TomalakGeret'kal: You're right, my bad. I just overflew it. Commented Nov 14, 2011 at 10:13
  • That said... do you want the answer in JavaScript, or CoffeeScript? Learn to be precise! Commented Nov 14, 2011 at 10:13

11 Answers 11

24
odd  = arr.filter (v) -> v % 2
even = arr.filter (v) -> !(v % 2)

Or in more idiomatic CoffeeScript:

odd  = (v for v in arr by 2)
even = (v for v in arr[1..] by 2)
Sign up to request clarification or add additional context in comments.

1 Comment

should be arr.filter((v, i) => i % 2) since OP's question is based on position not value
22

You could try:

var Arr1 = [1,1,2,2,3,8,4,6],
    Arr2 = [],
    Arr3 = [];

for (var i=0;i<Arr1.length;i++){
    if ((i+2)%2==0) {
        Arr3.push(Arr1[i]);
    }
    else {
        Arr2.push(Arr1[i]);
    }
}

console.log(Arr2);

JS Fiddle demo.

1 Comment

Man, I could be good at something, if I'd just avoid being distracted...sigh. Thanks! (And edited the link in..!) XD
4

It would be easier using nested arrays:

result = [ [], [] ]

for (var i = 0; i < yourArray.length; i++)
    result[i & 1].push(yourArray[i])

if you're targeting modern browsers, you can replace the loop with forEach:

yourArray.forEach(function(val, i) { 
    result[i & 1].push(val)
})

Comments

4

A functional approach using underscore:

xs = [1, 1, 2, 2, 3, 8, 4, 6]
partition = _(xs).groupBy((x, idx) -> idx % 2 == 0)
[xs1, xs2] = [partition[true], partition[false]]

[edit] Now there is _.partition:

[xs1, xs2] = _(xs).partition((x, idx) -> idx % 2 == 0)

Comments

1
var Arr1 = [1, 1, 2, 2, 3, 8, 4, 6]
var evenArr=[]; 
var oddArr = []

var i;
for (i = 0; i <= Arr1.length; i = i + 2) {
    if (Arr1[i] !== undefined) {
        evenArr.push(Arr1[i]);
        oddArr.push(Arr1[i + 1]);
    }
}
console.log(evenArr, oddArr)

Comments

0

I guess you can make 2 for loops that increment by 2 and in the first loop start with 0 and in the second loop start with 1

Comments

0

A method without modulo operator:

var subArr1 = [];
var subArr2 = [];
var subArrayIndex = 0;
var i;
for (i = 1; i < Arr1.length; i = i+2){
    //for even index
    subArr1[subArrayIndex] = Arr1[i];
    //for odd index
    subArr2[subArrayIndex] = Arr1[i-1];
    subArrayIndex++;
}
//For the last remaining number if there was an odd length:
if((i-1) < Arr1.length){
    subArr2[subArrayIndex] = Arr1[i-1];
}

2 Comments

This is not the simplest way.
well, I agree I should a change the first sentence and write: "a method without modulo calculation"
0

Just for fun, in two lines, given that it's been tagged coffeescript :

Arr1 = [1,1,2,2,3,8,4,6]

[even, odd] = [a, b] = [[], []]
([b,a]=[a,b])[0].push v for v in Arr1

console.log even, odd
# [ 1, 2, 3, 4 ] [ 1, 2, 8, 6 ]

Comments

0

As a one-liner improvement to tokland's solution using underscore chaining function:

xs = [1, 1, 2, 2, 3, 8, 4, 6]
_(xs).chain().groupBy((x, i) -> i % 2 == 0).values().value()

Comments

0

filters is a non-static & non-built-in Array method , which accepts literal object of filters functions & returns a literal object of arrays where the input & the output are mapped by object keys.

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

Comments

0

You can use Object.groupBy (since ECMAScript 2024) for this. With destructuring your example can be processed like this:

const arr = [1,1,2,2,3,8,4,6];
const { even, odd } = Object.groupBy(arr, (_, i) => i % 2 ? "odd" : "even");
console.log(even);
console.log(odd);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.