In: Computer Science
The Javascript code to seperate even, odd numbers from a list
is:
//Creating a array with some numbers
var nums = [11,29,32,24,55,94,33,1,19,47,54,66,17];
//Creating two more arrays to store even and odd numbers seperately
var evens = [];
var odds = [];
//A function evenNumbers(nums) t seperate even,odd numbers in nums list
var evenNumbers = function(nums) {
//Iterating through every number in nums list using for loop
//nums.length returns length of nums array
for (var i = 0; i < nums.length; i++) {
//If the number at index i in nums array is divisible by 2 then it is even.
//a%b gives the remainder when a is divided by b
if ((nums[i] % 2) == 0) {
//Adding this number to even array
evens.push(nums[i]);
}
//Else it is odd number
else {
//Adding this number to odd array
odds.push(nums[i]);
}
}
};
//calling evenNumbers() function
evenNumbers(nums);
//Displaying even numbers, odd numbers arrays seperately
console.log("Even numbers in given list: ");
console.log(evens);
console.log("Odd numbers in given list: ");
console.log(odds);
I have declared and initialized a array called nums[] with some numbers. The I have created two more empty arrays even[ ] and odd[ ] to store the even and odd numbers of nums[] array seperately. I have called a function evenNumbers(nums) which checks if a number in the nums[] array is even or odd by dividing it by 2 and checking if remainder is 0. If remainder is 0 then it will add the number to even[ ] array using push() function else it will add number to odds[] array using push() function. We check this to all numbers in array nums by using a for loop that iterates till loop variable is less than length of nums[ ] array.
Then i have printed the output to the console using console() function. I have provided comments in the code explaining the process. I have tested the code and validated output. I am sharing output screenshot for your reference.
You can change numbers in the list nums[] and check for different cases.
Hope this answer helps you.
Thank you :)