I try to make a function to return first the odd elements of the array and then the even ones. Tell me how to do it? thanks
export const sameParityFilter = (arr = []) => {
let result = arr.filter(function(elem) {
if (arr % 2 == 0) {
return true;
} if (arr % 2 != 0) {
return false;
}
});
sameParityFilter([[-1, 0, 1, -3, 10, -2]]);
sameParityFilter([[2, 0, 1, -3, 10, -2]]);
I didnot understand the code you have written so I wrote a simple code which shall help you
const sameParityFilter = (arr = [], filter = "odd") => {
const odds = []
const evens = []
for(item of arr) {
if(item % 2 === 0) {
evens.push(item)
} else {
odds.push(item)
}
}
if(filter === "odd") {
return odds
} else {
return evens
}
}
alert(sameParityFilter([1 , 7 , 5 , 6 , 7 , 1 , 2] , "even"))
alert(sameParityFilter([1 , 7 , 5 , 6 , 7 , 1 , 2]))
To create an output array filled with all the odd entries which are then followed by all the even entries of an input array, while preserving the order of values' appearance in the input array, try using Array.prototype.reduce with a two-dimensional array accumulator argument, followed by a call to Array.prototype.flat to concatenate the odd and even sub-arrays:
const oddsFirst = arr=>arr.reduce((acc,n)=>(acc[n&1^1].push(n), acc),[[],[]]).flat()
console.log(oddsFirst([-1, 0, 1, -3, 10, -2]));
Array.prototype methods reduce and flat are available on MDN, andn&1^1 get the least significant binary digit of n by anding n with 1, followed by exclusive-oring the result with 1 to flip ones to zeros and zeroes to ones. The result is zero for odd numbers and one for even numbers..flat() call.const sameParityFilter = (arr)=>{
let odd = [];
let even = [];
arr.forEach(elem => {
if(elem%2==0)
even.push(elem)
else
odd.push(elem)
})
return [odd,even];
}
console.log(sameParityFilter([-1, 0, 1, -3, 10, -2]));
console.log(sameParityFilter([2, 0, 1, -3, 10, -2]));