skip to Main Content

I’m writing a calculator app. Buttons in html add elements to an array. When the user hits =, it will iterate through the array and combine numbers that have no mathematical symbol between them. However, I have to remove an element each time 2 numbers are 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 have tried iterating the length of the array backwards which broke it more.
I’ve tried different versions of splice including

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

Current output with equation.splice[i] is [12,23,3,"/",12,23,3]. It should be [123,"/",123]

4

Answers


  1. You are confusing [ ] (index/property access) and ( ) (function call). It should be equation.splice(i, 1).

    Also, please note that removing an item will shift the other indices, so you will then skip one item unless you manually decrement your counter with i-- or iterate backwards instead of forwards.

    Also, I’m not sure why you manually skip the next item in your else, is that intentional? Perhaps there should not be any else?

    Login or Signup to reply.
  2. This should work. If found multiple problems.

    1. The check for checking if the equation is a number is wrong.
    2. equation.splice needs to have these ( ) instead of these [ ] because it’s a function
    3. i++; in the else block is not needed
    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;
    }
    
    Login or Signup to reply.
  3. Splicing the array and modifying the length of it while iterating over it at the same time can cause all sorts of different issues. I tried a different approach where I form numbers iteratively and push them to the result array once formed.

    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;
    }
    Login or Signup to reply.
  4. Use array.splice(index, deleteCount, ...items) to replace the items in array:
    (and use i-- to repeat loop on the same index)
    (and use unary + to convert to number if you convert to string by adding a string, I guess)

    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
        {
          let text = '' + equation[i - 1] + equation[i]; //combines equation[i] and the index before 
          equation.splice( /*start*/ i - 1, /*deleteCount*/ 2, /*...items*/ +text); //replace them with a number
          i--; // repeat same i
        }
    
      }
      console.log(equation);
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search