Created
August 14, 2018 00:18
-
-
Save Samuelachema/f2ed638726cac797391616d2286aadc1 to your computer and use it in GitHub Desktop.
Write a mySort function which takes in an array integers, and should return an array of the inputed integers sorted such that the odd numbers come first and even numbers come last.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
JavaScript | |
Write a mySort function which takes in an array integers, and should return an array of the inputed integers sorted such that the odd numbers come first and even numbers come last. | |
For exampl1e: | |
mySort( [90, 45, 66, 'bye', 100.5] ) | |
should return | |
[45, 66, 90, 100] | |
*/ | |
function mySort(nums) { | |
let evens = []; | |
let odds = []; | |
for (let i = 0; i < nums.length; i++) { | |
if(typeof nums[i] === "number"){ // ignore if its not a number | |
if ((nums[i] % 2) === 1) { | |
odds.push(parseInt(nums[i])); | |
} | |
else { | |
evens.push(parseInt(nums[i])); | |
} | |
} | |
} | |
let numsArray = odds.sort((a, b) => a - b).concat(evens.sort((a, b) => a - b)); | |
return numsArray; | |
} |
function mySort(nums) {
let evens = []; //empty array for even number
let odds = []; //empty array for odd number
//looping through
for (let i = 0; i < nums.length; i++) {
if(typeof nums[i] === "number"){ // ignore if its not a number
//check if the number is an odd number ,if the remainder after the division(modulo division) is 1
//the test is true then the number is odd
if ((nums[i] % 2) === 1) {
//push the element into the (odds) array .
odds.push(parseInt(nums[i]));
}
else {
//push the element into the (evens) array .
evens.push(parseInt(nums[i]));
}
}
}
let numsArray = odds.sort((a, b) => a - b).concat(evens.sort((a, b) => a - b));
return numsArray;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
help me learn this please suggest any thing ...i get my learning material from net with no instructor