Adding together separate numbers within an array using JavaScript

I am currently working on a task that involves summing up all the numbers in each array and displaying the total sum of that specific array. Unfortunately, I am facing challenges in figuring out how to achieve this functionality through my code.

For example:

var myArray = [123, 456, 789]

My aim is for the program to output 6, 15, 24.

This means adding up each individual number within the array: 1+2+3=6, 4+5+6=15, and 7+8+9=24.

I would greatly appreciate some guidance on how to approach this problem of adding every single number in the input array.

Answer №1

To achieve this, you can utilize the Array#map and Array#reduce methods.

If you prefer using ES2015's Arrow Function syntax:

myArray.map(el => el.toString().split('').reduce((sum, b) => sum + +b, 0));

var myArray = [123, 456, 789];

var resultArr = myArray.map(el => el.toString().split('').reduce((sum, b) => sum + +b, 0));

console.log(resultArr);
document.body.innerHTML = resultArr; // FOR DEMO ONLY

In older versions like ES5:

myArray.map(function (el) {
    return el.toString().split('').reduce(function (sum, b) {
        return sum + +b
    }, 0);
});

var myArray = [123, 456, 789];

var resultArr = myArray.map(function (el) {
    return el.toString().split('').reduce(function (sum, b) {
        return sum + +b
    }, 0);
});

console.log(resultArr);
document.body.innerHTML = resultArr;

Answer №2

To break down each number into its individual digits, you can utilize the modulo operator.

For instance, using X mod 10 will extract the rightmost digit from X, while removing the last digit of X requires integer division, denoted as X div 10.

function analyzeDigits(array) {
  return array.map(function(item) {
    var sum = 0;
    while (item > 0) {
      sum += item % 10;
      item = Math.floor(item/10);
    }

    return sum;
  });
}

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

Transform into binary and divide into separate elements within an array

Looking to transform a decimal number into binary and then partition it into an array. For instance: If the number is 5, it will become 101 and the array will be {1, 0, 1}. Alternatively, if the number is 26, it will be converted to 11010 and the array ...

Guide to playing a gif solely through an onclick event using JavaScript

Below you will find a code that is used to load a gif animation from an array of characters, and then display it within a board class using the image src. I am looking to make the gif animation play only when the displayed gif is clicked. Currently, the ...

Retrieve the value of a variable in a Bootstrap modal using Jade

I am looking to accomplish the following: On my Jade page, I have a for-loop that generates a list of items. Each item has some information displayed through Jade variables and a delete button. When this delete button is clicked, I want a Bootstrap Modal ...

ReactJS is making a controlled input of type text into an uncontrolled component with the help of a component transformation

I am encountering a situation where I fetch data from the server and set values in the state for controlled inputs. For example, if I have an input field with a value of this.state.name, I retrieve the name "Dave" from the server and set it in the state as ...

Error message: "Unable to access D3 data when trying to select nested

Working with JSON data in D3 is proving to be a challenge for me. The file seems to be properly read, as indicated by its appearance when I use console.log, and it appears to be correctly formatted based on the examples I have come across. However, when I ...

Decoding the file's encoding: A beginner's guide

I need help determining the encoding of a file in order to only upload CSV files with utf-8 format. If there are any non utf-8 characters, I want to display an error message. Currently, I am utilizing Papa Parser for parsing. Is there a way to detect the ...

Exploring front-end AJAX functionality within a WordPress plugin

As a newcomer to WordPress development, I have been working on writing an AJAX request within a WordPress plugin. To test this functionality, I initially sent the request to an external non-WP server where it worked without any issues. Following the guidel ...

Is there a way to ensure that a "loop once" animated GIF background will replay on each page refresh or load?

I currently have an animated GIF file set as the background image for my div, which was specifically configured in Photoshop to loop only once. Therefore, it only plays on the initial page load. Is there a way to reset the background image upon page refre ...

Add CSS styles to the outermost container element when the slideshow is currently in use

On my homepage, I have a carousel featuring multiple slides. However, when the third slide appears in the carousel, the positioning of the carousel buttons within the div class="rotator-controls" shifts downward due to the space taken up by the image. My o ...

Ways to grant entry to a Vue.js page exclusively to authenticated users or when localStorage is present

My Vue.js application is set up with vue-router as shown below. index.html <p> <router-link to="/" exact> Home </router-link> <router-link to="/about"> About </router-link> <router-link to="/contact"> Contact < ...

Creating a recursive function to compute the average of elements within multi-dimensional arrays

How can I recursively loop through this multi-dimensional array while calculating the average by Standards? Here is the initial array, followed by my code (which loops through each level - not ideal), and then the Output. I'm seeking a function to op ...

Create a structure for objects that can be easily cloned

Is there a way to automatically restructure a JavaScript object to be cloneable by eliminating all of its methods? In my particular scenario, I am generating three.js BufferAttribute objects in a web worker and need to transmit them to the main thread. C ...

Adding a uniform header and footer across all pages simultaneously in HTML

I am currently working on a project where I want to apply the same header and footer design from my homepage to all pages. However, I need a method that allows me to update the header and footer in one place, so that any changes I make will automatically r ...

What is the best way to serialize data from non-form elements and make it easily accessible through params[:model]?

I have developed a unique Sinatra application that leverages an external API to load data and exhibit it on a page. Utilizing Sinatra, the information is retrieved and stored in a temporary model instance (which is NOT saved) for seamless access to all its ...

Select2 using AJAX: chosen option disappears upon receiving AJAX response

Despite going through numerous questions and answers, the issue persists. Here is an excerpt of the code in question: <div class="col-md-2"> <label for="wh_location">{{ __('reports.warehouse_movement.location') ...

Unable to conceal the innerHTML once the error has been rectified

My error messages are displayed using innerHTML. How can I make them disappear once the error is corrected? Currently, they stay on, even after the error is fixed. I tried resetting them at the top of the script but it didn't work. Link to JSfiddle ...

The latest URL is not launching in a separate tab

Looking for some assistance with this code snippet: <b-btn variant="primary" class="btn-sm" :disabled="updatePending || !row.enabled" @click="changeState(row, row.dt ? 'activate' : 'start&apo ...

Using Gmail with Nodemailer is throwing an error: "Cannot add property 'mailer' on a string with value 'SMTP'."

I am facing an issue with sending data from a form to my Gmail account. Whenever I click the submit button, I encounter the same error message repeatedly. Despite researching various problems related to nodemailer, none of them match the specific problem t ...

How to eliminate a particular item within a string only in rows that include a different specific item using JavaScript

Is my question clear? Here's an example to illustrate: let string = "Test text ab/c test Test t/est ### Test/ Test t/test Test test" I want to remove / only from the line that includes ###, like so: Test text ab/c test Test t/est ### Test T ...

Why is the jQuery Ajax AutoComplete feature not functioning properly?

Hey there, I'm currently utilizing CodeIgniter along with Ajax AutoComplete for jQuery in my project. When setting up my autocomplete feature in jQuery, I used the following code: a = $('.city').autocomplete({ serviceUrl: "<? echo $ ...