i wants to separate an array with two groups (odd and even) sequentially. but when i try this:
why 4,8,6,2 instead of 2,4,6,8?
it is because you are modifying the same Array which you are looping through. to understand better, lets loop through your code
after
1st Loop: array: [1, 2, 3, 4, 5, 6, 7, 8, 9];
2nd loop: array: [1, 3, 4, 5, 6, 7, 8, 9, 2];
3rd loop: array: [1, 3, 5, 6, 7, 8, 9, 2, 4];
4th loop: array: [1, 3, 5, 7, 8, 9, 2, 4, 6];
5th loop: array: [1, 3, 5, 7, 9, 2, 4, 6, 8];
6th loop: array: [1, 3, 5, 7, 9, 4, 6, 8, 2];
7th loop: array: [1, 3, 5, 7, 9, 4, 8, 2, 6];
8th loop: array: [1, 3, 5, 7, 9, 4, 8, 6, 2];
9th loop: array: [1, 3, 5, 7, 9, 4, 8, 6, 2];
to separate out odd/even in an array,
we will have to filter out odd and even separately and push evenArray
in the end of oddArray
(filtered Array)
var input = [1, 2, 3, 4, 5, 6, 7, 8, 9];
input = input.sort((a, b)=> a-b); //to sort array if not sorted already
var evenArr = [];
input = input.filter(item => {
if (item % 2 != 0)
return true
else {
evenArr.push(item);
return false;
}
})
Array.prototype.push.apply(input, evenArr);
console.log(input);