Skip to content

Instantly share code, notes, and snippets.

@Samuelachema
Created August 14, 2018 00:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Samuelachema/f2ed638726cac797391616d2286aadc1 to your computer and use it in GitHub Desktop.
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.
/*
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;
}
@SerwaddaUG
Copy link

help me learn this please suggest any thing ...i get my learning material from net with no instructor

@DidierManiraho
Copy link

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