1

I'm new to coding and trying to figure out nested javascript functions. I've searched other questions but still can't figure it out. I'd like a function that takes a string of numbers seperated by spaces, converts the string to an array, and then outputs the result of a mathematical function on the array.

I've written something using the following outline and it works, but seems messy and don't know that I am really doing it the best way. I don't really understand how to call a function from another function.

    function doMathOnThisString(string) {
        var ar = convertStringToArray(string);
        return doMathOnArray(ar);

        function convertStringToArray(string) {
            //code that converts the original input string to an array
            return (ar)
        };

        function doMathOnArray(a) {
            //code that does math on an array
        }; 
}
2
  • Change return (ar) to return the result of the function. Commented Mar 9, 2018 at 23:46
  • var result = string.split(' ').reduce((a,v)=> a * v); math function goes inside the "reduce"...see details on how reduce works here Commented Mar 9, 2018 at 23:49

1 Answer 1

1

You're doing just fine with what you have, just take it a step further and you'd be fine. Kindly see my solution below:

function doMathOnThisString(string) {
  // Converts a string of numbers separated by spaces to an array
  function convertStringToArray(input) {
    return input.split(' '); // split input on spaces
  };

  // Sums up the value in the array of number string
  function doMathOnArray(numbersString) {
    return numbersString
      .map((number) => Number(number)) // Convert each (string) number to a proper number
      .reduce((acc, curr) => acc + curr); // Add each number
  };
  
  
  var stringNumberArray = convertStringToArray(string);
  return doMathOnArray(stringNumberArray);
}

const result = doMathOnThisString('1 2 3 4 5 6 7 8');
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.