Combining numerical values within an array using JavaScript

Below are different buttons ranging from 1 to 9 that I have:

<button type="button" onclick="calculatorNumber(1)">

When clicked, the following function is triggered:

function calculatorNumber(i) {
    myNumbers.push(i);
    var x = document.getElementById("screen").innerHTML = myNumbers.join("");

However, the function is not working as intended. For example, if I click on 3 and then 4, instead of storing them together as '34', they are stored separately at [0] and [1]. Any ideas on how to make them store as one value?

I attempted to improve the function with the following code, but it did not resolve the issue:

function calculatorNumber(i) {
    myNumbers.push(i);
    var x = document.getElementById("screen").innerHTML =  myNumbers.join(""); // joining into one without comma
    myNumbers = []; // emptying the array
    myNumbers.push(x); // pushing the new combined value back in

Answer №1

Forget about arrays of numbers - all you need is one single number:

theOneNumber = theOneNumber * 10 + i;

Begin with a starting value of 0.

When you press 3 => the number becomes 3

Pressing 4 => the number transforms into 34

And pressing 5 => the number changes to 345

Answer №2

To maintain the sequence, make sure to enter the numbers in the correct order. It is advised to omit the following line:

myNumbers = []; //then empty the array altogether

Test run

var myNumbers = [];

function addToCalculator(i) {
    myNumbers.push(i);
    document.getElementById("screen").innerHTML =  myNumbers.join("");
}

function clear() {
    myNumbers = [];
    document.getElementById("screen").innerHTML =  "";
}
<div id="screen"></div><br>
<button type="button" onclick="addToCalculator(1)">1</button>
<button type="button" onclick="addToCalculator(2)">2</button>
<button type="button" onclick="clear()">CL</button>

Adding numbers

var myNumbers = [0], operator = [];

function addToCalculator(i) {
    myNumbers[myNumbers.length - 1] = myNumbers[myNumbers.length - 1] *10 + i;
    updateScreen();
}

function clear() {
    myNumbers[myNumbers.length - 1] = 0;
    updateScreen();
}

function add() {
    operator.push(p);
    myNumbers.push(0);
    updateScreen();
}

function p(b, a) {
    myNumbers.push(a + b);
}

function equals() {
    operator.length && operator.pop()(myNumbers.pop(), myNumbers.pop());
    updateScreen();
}

function updateScreen() {
    document.getElementById("screen").innerHTML =  myNumbers[myNumbers.length - 1];
}
<div id="screen">0</div><br>
<button type="button" onclick="addToCalculator(1)">1</button>
<button type="button" onclick="addToCalculator(2)">2</button>
<button type="button" onclick="clear()">CL</button>
<button type="button" onclick="add()">+</button>
<button type="button" onclick="equals()">=</button>

Answer №3

Here's a quick solution for your current issue:

 let lastIdx = listNumbers.length - 1;
 listNumbers[lastIdx] = listNumbers[lastIdx] * 10 + index;

But, the approach to handling operators is still unknown.

Answer №4

To combine the numbers in your array and convert them to strings as you go, simply loop through each number and concatenate it to a string.

For instance:

myNums = [1, 2, 3]
var text = '';

for (i = 0; i < myNums.length; i++) {
    text += myNums[i].toString();
}

This will result in '123'

Next:

var x = document.getElementById("screen").innerHTML = text;

You could split this into two functions:

var myNumbers = [];
text = '';

function getMyNumber(i){
    myNumbers.push(i);
    }
function getText(myNumbers){
    for (i = 0; i < myNumbers.length; i++) {
    text += myNumbers[i].toString();
    }
    }

Call these functions accordingly (loop through calling the first one, I'm not sure how you're getting input though, then call the second function with myNumbers as an argument) and display the result on your 'screen'. Both variables are global in this case.

I hope this explanation is helpful.

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

Is there a way to provide a dynamic value for the p:remoteCommand ajax call?

My issue involves a p:dataTable that contains p:commandLink elements. I need to initiate an ajax call with parameters when the mouseover event occurs. After some research, it became clear that commandLink cannot trigger an ajax call on mouseover directly - ...

What is the best way to establish a connection between two applications using React and Node

Currently, I am facing a challenge with integrating two separate applications. One is a login/registration form written in Node.js, Express.js, React.js, and MySQL. The file structure looks like this: https://i.sstatic.net/th6Ej.png The other application ...

How can I limit the input of string values from a Node Express request query?

export type TodoRequest = { order?: 'asc' | 'desc' | undefined; } export const parseTodoRequest = (requestData: ParsedQs): TodoRequest => { return { order: requestData.order as 'asc' | 'desc' | u ...

Data not being saved when using the Post method in a Web API

I built a straightforward Web API application that allows users to GET or POST data. The data consists of a simple array of Strings like ["foo", "bar"]. However, when I try to send data using the POST method to the Web API and then make another call to ret ...

Step-by-step guide on adding and removing a row from a table with the help of jquery and node js

I just finished creating a table in jade that includes two select boxes and a single text box. However, I encountered an issue where my row addition functionality stops working after the user makes a selection in the first select box and then changes the ...

Strange response received from Stack Overflow API request

Having some issues with the code I'm using to call the Stack Overflow API: var request = require('request'); var url = 'http://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=node.js&intitle=node.js&sit ...

What is the method for setting and comparing collectionsjs equality?

I'm interested in utilizing the data structure. Within the factory method, you have the opportunity to specify equals and compare parameters: SortedMap(entries, equals, compare). Can anyone provide insight into what the expected formats for these pa ...

The node server.js encountered an error - Module not found

After attempting to start my node server using the following command: node server.js An error was thrown: internal/modules/cjs/loader.js:905 throw err; ^ Error: Cannot find module 'fcc-express-bground' Does anyone have any solutions? ...

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

Issue encountered while constructing an array within the component data following the 'created' event

It's been a while since I've dealt with Vue.Js, so my memory is a bit fuzzy. I'm facing an issue where I can't seem to modify a data array within a function that is called in the created hook. My goal is to create a multidimensional ar ...

Transforming an ordinary JavaScript object into a class instance

As I was delving into Angular's documentation on "Interacting with backend services using HTTP", I came across the following statement in the "Requesting a typed response" section: ...because the response is a plain object that cannot be automatical ...

What is the method to deactivate all events in React components using refs?

Currently, I am utilizing TreeView from Material-ui along with a text field for searching other items on the screen. Although TreeView and TextField are unrelated components. However, I have encountered an issue where if I click on a TreeView node and the ...

Attempting to modify background by manipulating the state in Reactjs

I'm currently working on an app that features various games. My goal is to allow users to click a button and have the game display on the screen, with the background color changing as well. I aim to utilize state to control the overall background of t ...

Using HTML and jQuery to create a table with buttons to add or remove rows is a common practice. However, there

I have created a simple table with an "Add Row" button. Each new row has a "Remove" button. However, I am facing an issue in binding the 'click' event for the class 'remove'. Here is the code snippet: <script src="https://ajax.googl ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

a guide on accessing key value elements within an array using Ionic 3

Just diving into the world of Ionic, I am currently working on a task to showcase products on the cart page that have been added to the cart. Upon fetching data from a REST API, I can see the response below in the console. "items": { "29.2.2.0.YTowOnt ...

The TypeScript compiler is generating node_modules and type declaration files in opposition to the guidelines outlined in the tsconfig.json file

For the past week, I've been trying to troubleshoot this issue and it has me completely puzzled. What's even more puzzling is that this app was compiling perfectly fine for months until this problem occurred seemingly out of nowhere without any c ...

Various ways to utilize Apollo's Query property

There are a couple of ways I've come across to utilize the new Query and Mutation props from Apollo. However, I've only been able to successfully implement one of them. First, defining the query within the Query prop directly like this: <Qu ...

Ensure the camera flag remains set in three.js

I am currently experimenting with the WebGLRenderer in three.js and I am looking for a way to keep the camera in motion without resetting, similar to how it is shown in this video at the 4:00 minute mark. You can view the video here: https://www.youtube.c ...

A custom Mongoose schema attribute configured with distinct values

I've been working on some code and here is what I have: var userSchema = new mongoose.Schema({ email: String, password: String, role: Something }); I'm aiming to set specific values ('admin', 'member', 'guest&apos ...