Issues arise when the Javascript splice function fails to properly combine array elements

My latest project involves developing a calculator application. The buttons in the HTML code add elements to an array, and when the user presses "=", the app is designed to iterate through the array. It combines numbers that are directly next to each other without any mathematical symbols between them. However, I encountered a challenge where I have to remove an element every time two numbers are successfully combined.

let equation = [1,2,3,"/",1,2,3];
combineNumbers();

function combineNumbers()//call to start finding solution by merging numbers
{
for(let i = 1; i < equation.length;i++)//iterates length of equation starting at 1
{
    if(isFinite(equation[i-1]) && isFinite(equation[i]))//checks if equation[i] and the index before it are numbers
    {
        equation[i-1] = '' + equation[i-1] + equation[i];//combines equation[i] and the index before
        equation.splice[i];//removes element at index i
    }
    else
    {
        i++;
    }

}
console.log(equation);
}

I experimented with iterating the length of the array backwards, but it only made things worse. Additionally, I tried various versions of the splice method, including

equation.splice[i]
equation.splice[i,1]

The current output using equation.splice[i] displays [12,23,3,"/",12,23,3], while the desired outcome should be [123,"/",123]

Answer №1

You seem to be mixing up [ ] (index/property access) and ( ) (function call). The correct syntax should be equation.splice(i, 1).

Additionally, keep in mind that removing an item will cause the other indices to shift, which means you will skip one item unless you manually decrease your counter with i-- or iterate backwards instead of forwards.

On another note, it's unclear why you are intentionally skipping the next item in your else statement. Perhaps there shouldn't be any else at all?

Answer №2

By splicing the array and adjusting its length during iteration, it can lead to various complications. I opted for a different method where I gradually construct numbers and then add them to the result array once they are complete.

let equation = [1,2,"*",3,"/",1,2,3,"+",4];
combineNumbers();

function combineNumbers()//call to start finding solution by merging numbers
{
    let result = [];
  var currentNumberStr = "";
  for (var i = 0; i < equation.length; i++) {
    let symbol = equation[i];
    if (isFinite(symbol)) {
        currentNumberStr += symbol; // if symbol is a number, append to current number string
    } else {
        // Otherwise, we hit an operator. Push the current number str e.g. "123" and the operator to the result array
      result.push(currentNumberStr);
      result.push(symbol);
      // Reset the current number string
      currentNumberStr = "";
    }
  }
  // At the end, you have a currentNumberStr left over (the end 123). Push that
  result.push(currentNumberStr);
  
  console.log(result);
  
  return result;
}

Answer №3

Utilize

array.splice(index, deleteCount, ...items)
in order to swap out the elements within an array:
(and make use of i-- to loop again on the same index)
(and utilize unary plus (+) to convert to a number if converting to string by concatenating strings, I assume)

let equation = [1, 2, 3, "/", 1, 2, 3];
combineNumbers();

function combineNumbers() //call to begin the process of merging numbers
{
  for (let i = 1; i < equation.length; i++) //iterates over the length of the equation starting from 1
  {
    if (isFinite(equation[i - 1]) && isFinite(equation[i])) //checks if equation[i] and the index before it are both numbers
    {
      let text = '' + equation[i - 1] + equation[i]; //concatenates values at equation[i] and the previous index 
      equation.splice( /*start*/ i - 1, /*deleteCount*/ 2, /*...items*/ +text); //replace them with a numeric value
      i--; // repeat the same i
    }

  }
  console.log(equation);
}

Answer №4

This seems to be functioning properly, but there are a few issues that need to be addressed.

  1. The check for determining if the equation is a number is incorrect.
  2. The method equation.splice should use parentheses ( ) instead of brackets [ ] since it is a function.
  3. The line i++; in the else block is unnecessary.
function combineNumbers()//call to start finding solution by merging numbers
{
    // Save output to local var
    let output = 0;

    //iterates length of equation
    for(let i = 0; i < equation.length;i++)
    {
        //checks if equation[i] is a number
        if(typeof equation[i] === 'number')
        {
            // Adds value to total values var
            ouput += equation[i];
        } else {
            // If equation is not a number do your other stuff here
        }

    }
    // Reset the equation var
    equation = [];
    
    // Log the output
    console.log(ouput);
    return ouput;
}

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

Swapping out 'useResult' in graphql for Vue and Apollo: A step-by-step guide

I need to replace the useResult function that is fetching data from GraphQL with a computed function. const locationOptions = useResult( result, [], ({ getLocations }): Option[] => formatOptions(getLocations) ) Instead, I want ...

Generating a JSON object using HTML select elements

Looking to generate a JSON string that includes select values and inner HTML values in a map format. For example: <select id="my-select"> <option value="1">one</option> <option value="2">two</option> </select> var json ...

Challenges with handling JSON data in JavaScript

I am currently attempting to retrieve and parse JSON data in order to display it on a blank HTML file. Unfortunately, I keep encountering an issue where if I retrieve and parse the data, I receive an error stating Uncaught TypeError: Cannot read property & ...

Fade-in loader with centered placement on the full page

As a newcomer to programming, I wanted to implement a loader that displays a centered loading animation when the page loads or refreshes. The animation should gray out and fade the entire page until it fully loads. I've managed to get everything else ...

(Original) redirect from specific url / url detection New text: "Redirection

Sorry for the long and confusing question, my apologies for wasting your time. I am still learning programming and what I really wanted to ask is "how can I retrieve a GET parameter using JavaScript?" Apologies for any inconvenience. ...

AngularJS approach to binding window scroll

Hey there, I'm a newcomer to AngularJS with a background in jQuery. I'm trying to create a fixed-top navbar using AngularJS that has a background which changes from transparent to opaque as the window is scrolled. Unfortunately, I'm struggli ...

What is the best way to save data from a jQuery plugin to a database using ASP .NET MVC?

I have a jQuery plugin called "Slider" that displays the current price of an item. I would like to enhance it by allowing users to change prices using the jQuery slider and update them in the database. Here is the model: public class Item { public in ...

How to effectively transfer a JSON object from a Python function to JavaScript using Eel, allowing you to seamlessly utilize and modify the JSON data

Let's delve into a slightly confusing question together. Have you heard of Eel? It's a Python module that lets you use functions created in Python in Javascript, and vice versa. What I want to achieve is taking a JSON object generated by a Python ...

Error in AJAX transmission

I am encountering an unusual issue with the jQuery ajax function in my script. The problem is specific to my friend's computer, as I am not experiencing any difficulties on my own computer. While attempting to utilize the error function property to ...

Show the result as "Content-Type: image/jpeg" on the webpage

I have a URL for an API request that automatically downloads and saves a QR code image from the browser. The Content-Type of the URL is application/jpeg, and its format looks like this: application(websiteURL)/egs?cmd=gen_qrcode&customer_id=123&n ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

Is there a way to retrieve the timestamp of a DOM change event when using MutationObserver for event tracking?

Currently, I am successfully using MutationObserver to monitor changes in the DOM. However, I would like to include a timestamp for each event. Unfortunately, there doesn't seem to be a timestamp property available in the MutationRecord. https://deve ...

Param values not being transferred via AJAX POST request

In my web application using Struts and Velocity, I'm facing an issue where JavaScript needs to pass a parameter to a method in a Java class. I have tried using an AJAX post call to a servlet, but I am not able to receive the parameter in the action cl ...

The product has been taken out of the cart, yet it has not been reinserted into the cart

The product disappears from the cart after clicking on Add to Cart, but it doesn't reappear when clicked again. //function for adding only one item to cart document.getElementById('btn1').onclick = function() { addItemToCart() }; fun ...

What is the best way to iterate through JSON objects stored in a single location?

Currently, I am dealing with a single JSON object structured as follows: Object --> text --> body --> div Array[20] --> 0 Object --> text --> body --> div Array[20] --> 1 Object --> text --> body --> div Array[20] --> . ...

Is It Possible to Determine If a Checkbox Has Been Checked?

Here's what I have now: I have a checkbox that I need to verify if it's selected. <input type="checkbox" name="person_info_check" value="0" &nbps>Read and agree!</input> However, the method I found online to verify the checkbox ...

Angular and D3.js: Enhancing StackedBar Chart ToolTips with Added Functionality

I have modified the code from this example to be compatible with the latest versions of Angular and D3. Although it works well after a small tweak, I am unable to see the tooltips when hovering over the chart... https://i.sstatic.net/Rpebe.png <h3> ...

No search results found for Mongoose text search query

Despite using Mongoose 5.7.8 for my app, the text search feature is not yielding any results. Below is a schema/model example: import mongoose, { Document, Schema } from 'mongoose'; import { Moment } from 'moment'; import { IUser } fr ...

Exploring the functionality of utilizing dual loops with v-for in Vue.js

I am facing an issue with my table code where I need to repeat it 6 times to match the day column above. I would like to use v-for and make use of a variable called "count" which represents the number of days. Can someone assist me with this task? <tabl ...

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...