Stan
Stan

Reputation: 63

Take array and push odd and even numbers into separate arrays

I have an array with one letter/two number formatted elements in it and need to split the elements in the original array into the other two arrays, by odd and even numbers, and keep the original array intact. I have looked through a lot of other questions here, but none seem to fit.

I have been looking at some javascript code that works when the array elements are numbers only, but it won't work with the leading letter added. Here is the code:

var h = [06, 03, 02, 13, 04, 05, 12, 07, 09, 01, 11, 22];

e = [];

for (var i = 0; i < h.length; ++i) {
    if ((h[i] % 2) == 0) {
        e.push(h[i]);
    }
}
alert(e);

o = [];

for (var i = 0; i < h.length; ++i) {
    if ((h[i] % 2) == 1) {
        o.push(h[i]);
    }
}

alert(o);

This works fine (even though it drops the leading digit if it is a zero), but now if the array is changed to

var h = [B09,O67,I21,B04,B13,N34,N43,O74,O75,I26];

The code above does not work with the new array. I figure that I would need to filter out the odds and evens by looking at only the last number of each element, but I have not been able to figure out how to do so. The array elements are all in the same three character format of one letter followed by two digits and would have to retain this same format in their new arrays.

Thanks for any direction in this and a Happy Thanksgiving to all,

Stan...

Upvotes: 0

Views: 5615

Answers (2)

Shai
Shai

Reputation: 7307

I won't duplicate what's already been said, but I will add that you should combine the 2 loops into just one:

e = [];
o = [];

for (var i = 0; i < h.length; ++i) {
    if (/* h[i] is even */) {
        e.push(h[i]);
    } else {
        o.push(h[i]);
    }
}

alert(e);
alert(o);

Upvotes: 3

personne3000
personne3000

Reputation: 1840

Instead of :

h[i] % 2

You can just do :

parseInt(h[i].substring(1)) % 2

That is assuming you forgot the quotes in your example array, which should be :

var h = ["B09","O67","I21","B04","B13","N34","N43","O74","O75","I26"];

Upvotes: 4

Related Questions