Adding up and finding the contrast between odd and even numbers

After successfully segregating the odd and even numbers, I am faced with a challenge in determining how to add the odds together and the evens together before subtracting them to find the final result. For example:

(1 + 3 + 5 + 7 + 9) - (2 + 4 + 6 + 8) = 5

    let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    sumDiff(numbers);
    
    function sumDiff(numbers) {
        let even = [];
        let odd = [];
        
        for (let i = 0; i < numbers.length; i++) {
            if (numbers[i] % 2 === 0) {
                even.push(numbers[i]);
            } // end 
            else {
                odd.push(numbers[i]);
            }// end else
            
        } //end of for loop
        
        console.log(odd);
        console.log(even);
    } // end of function

While I don't need the complete solution at this point, I do require some direction on how to proceed. It seems logical to separate the odd and even numbers first, but should I create a new function or can this be accomplished within the existing one?

Answer №1

Your solution is working perfectly! To incorporate the additional functionality you seek, consider utilizing the Array.prototype.reduce() method to calculate the total sum of the two arrays you have generated. Here's an example implementation:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
calculateSum(numbers);

function calculateSum(numbers) {
    let evenNumbers = [];
    let oddNumbers = [];

    for (let i = 0; i < numbers.length; i++) {
        if (numbers[i] % 2 === 0) {
            evenNumbers.push(numbers[i]);
        } // end 
        else {
            oddNumbers.push(numbers[i]);
        }// end else

    } //end of for loop

    console.log(oddNumbers);
    console.log(evenNumbers);
    
    let sumOfOdd = oddNumbers.reduce((result, current) => result += current, 0)
    let sumOfEven = evenNumbers.reduce((result, current) => result += current, 0)
    
    console.log("Total sum of odd numbers: " + sumOfOdd)
    console.log("Total sum of even numbers: " + sumOfEven)
    console.log("Difference between sums: " + (sumOfOdd - sumOfEven))
} // end of function

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue when attempting to construct the project: it asks for callback functions, but instead received an [

I'm currently facing an issue while trying to access a function that is crucial for updating some database values. Whenever I attempt to build the project, I encounter the following error: Error: Route.post() requires callback functions but got a [ ...

Steps to dynamically update a dropdown list with the value of another field

I am currently working on a dropdown list featuring all countries. Here is the code snippet: <select id="Country" onchange="country();"> <option id="3">Japan</option> <option id="4">Canada</option> <option id="5"> ...

HashSet will remain empty as no elements are being added to it

I am struggling with filling a HashSet declared in my program with elements from an array that is also declared. Despite my efforts to troubleshoot by adding a text output, I can't seem to make it work. The text doesn't even appear in the output, ...

Extract all objects from an array where a specific field contains an array

data:[ { id:1, tags:['TagA','TagB','TagC'] }, { id:2, tags:['TagB','TagD'] }, { id:3, tags:[&a ...

2D Array Exception: Index Out of Bounds

In my programming scenario, I am working with a 2D array that has only one row but more than one column. double[][] T = new double[1][24]; System.out.println(T[1].length); When trying to print the length of the columns, it generates an "index out of boun ...

JS Difficulty with Applying Underline in Contenteditable

Recently, I encountered a glitch with document.execCommand that seems puzzling. Allow me to explain the situation at hand. $("#underline-btn").click(function() { document.execCommand("underline"); }); <script src="https://ajax.googleapis.com/ajax/l ...

Utilizing the keydown event in jquery with specific key restrictions

I want to prevent the page from refreshing when the user presses F5 or Ctrl+F5. I have come up with the following code to achieve this, but now whenever I press any key on the page, the function runs and prevents me from filling out textboxes or using ot ...

Attempting to persist a nested document in MongoDB using mongoose within a Nodejs environment

I attempted to save an address as a nested document in the following format When sending data from the client side, it was formatted like this: const address = JSON.stringify( { addressline1:form.addressline1.value, addressline2:form.addressline2.value, c ...

Exploring AngularJS to search for and present data in a tabular layout

Can anyone guide me on searching for data within a JSON file and presenting it in a table format? I want the table to be visible only when I click the search button. I would really appreciate it if someone could provide me with instructions or a helpful ...

Node is looking for a callback function, but instead received something that is undefined

When attempting to build a basic CRUD app in node js, an issue arises with the error message "Route.get() requires a callback function but got a [object Undefined]" specifically on the router.get("/:id", userController.getUser); line. Routes.js const expr ...

Enhancing Your Website Listings with Firebase: A Step-by-Step Guide to Updating

I am currently working on an admin panel for a website, utilizing Firebase as the backend database. I have successfully implemented the listings display feature, however, I'm facing an issue where clicking on a specific listing should change its statu ...

Using JSF 2.1 for Ajax autocomplete with server search triggered only when user pauses typing

Currently, I am working on developing an autocomplete feature that involves database search based on user input events (specifically onkeyup) in a <h:inputText />. There are two specific preconditions that need to be met for the application to perfo ...

Avoiding page refresh while utilizing the ng5-slider component in Angular

I am currently working with an ng5-slider that has a customizable range from 0 to 1000. However, I have encountered an issue when adjusting the slider at the bottom of the page - it refreshes and automatically takes me back to the top of the page. I would ...

Dropdown menu with multiple selection options

Is there a way to create a combobox that allows for multiple selections using either Javascript or HTML? While a typical combobox/dropdown structure does not support selecting multiple items, how can this functionality be achieved? ...

"Set a timeout for an HTML markup to be displayed in an AJAX

Is there a way to automatically hide the success message that appears after an AJAX request is successful? For example, after 2 seconds of displaying the message, I want it to disappear. Here's the code I have: $.ajax({ url : 'process/regis ...

Is there a way to replicate Twitter's "what's happening" box on our website?

Currently, I am trying to extract the cursor position from a content-editable box. However, when a new tag is created, the cursor appears before the tag instead of after it. Additionally, I am having trouble with merging/splitting the tags. Any suggestions ...

Dealing with a surprise JSON error in Express.js using Javascript

Dealing with Unexpected JSON in my express js application using try and catch. I attempted to achieve this as follows: try{ let body = JSON.parse(req.body); }catch(e){ res.json({ error:e }) } However, the Unexpected JSON error is not caught in ...

Guide to obtaining specific top elements from an array using JavaScript

I'm seeking assistance with sorting arrays in JavaScript. Here is an example of a sorted array: mainArray : [25 20 20 20 18 17 17 15 12 12 10 5 5 ] The mainArray may contain duplicate values. A. Dealing with duplicates Based on user input, I need ...

Validate AngularJS forms by displaying error messages based on the server's response

Within my form, I am checking for the existence of an email address. If the email already exists, I display an error message from the JSON response when the user clicks the submit button. When the email already exists, I receive a 409 error. I am looking ...

having difficulty implementing the blur effect in reactJS

Currently, I am working on developing a login page for my project. Below is the code snippet I have implemented for the functionality: import React, { useState, createRef } from "react"; import { Spinner } from "react-bootstrap"; import ...