In: Computer Science
6.15 LAB: JavaScript arrays
Write the function divideArray() in script.js that has a single numbers parameter containing an array of integers. The function should divide numbers into two arrays, evenNums for even numbers and oddNums for odd numbers. Then the function should sort the two arrays and output the array values to the console.
Ex: The function call:
var nums = [4, 2, 9, 1, 8]; divideArray(nums);
produces the console output:
Even numbers: 2 4 8 Odd numbers: 1 9
The program should output "None" if no even numbers exist or no odd numbers exist.
Ex: The function call:
var nums = [4, 2, 8]; divideArray(nums);
produces the console output:
Even numbers: 2 4 8 Odd numbers: None
Hints: Use the push() method to add numbers to the evenNums and oddNums arrays. Supply the array sort() method a comparison function for sorting numbers correctly.
To test your code in your web browser, call divideArray() from the JavaScript console.
script.js :
//function divideArray()
function divideArray(nums) {
//declaring array to store oddNumber
var oddArray = [];
//this is the array which stores even number
var evenArray = [];
//using for loop
for (var i = 0; i < nums.length; i++) {
//checking value of i
if (nums[i] % 2 == 0) {
//when even number is found then
//push element into even array
evenArray.push(nums[i]);
}
else {
//when odd number is found then
//push element into odd array
oddArray.push(nums[i]);
}
}
//test the odd and even array
evenArray.sort();
oddArray.sort();
//print even numbers
console.log("Even numbers:");
//checking array length
if (evenArray.length > 0) {
//when evenArray conatins elements then
//print even numbers
//using for loop
for (var i = 0; i < evenArray.length; i++) {
console.log(evenArray[i]);//print element
}
}
else {
//when evenArray has no any element then print
console.log("None");
}
//print odd numbers
console.log("Odd numbers:");
//checking array length
if (oddArray.length > 0) {
//when oddArray conatins elements then
//print odd numbers
//using for loop
for (var i = 0; i < oddArray.length; i++) {
console.log(oddArray[i]);//print element
}
}
else {
//when oddArray has no any element then print
console.log("None");
}
}
//declare array with numbers
var nums = [4, 2, 9, 1, 8];
//call function divideArray()
divideArray(nums);
======================================
Screen when function is called with array [4, 2, 9, 1, 8] :
Screen when function is called with array [4, 2, 8] :