Skip to content
Advertisement

get the number of inputs given to a function js

Assume i have created a function function findInputGiven(){} and i called it somewhere below twice findInputGiven([1, 2], [3, 4]), findInputGiven([1, 2], [3, 4], [5, 6]). This function can be called with multiple inputs, i dont know how many inputs will be available in my findInputGiven function. How can i get the number of inputs given to call function.

My task is to return an array of all numbers of given arrays. If the function is called like findInputGiven([1, 2], [5, 6]), then i should return [1, 2, 5, 6].

Advertisement

Answer

My task is to return an array of all numbers of given arrays

What you can do is use rest parameters to get an array of all arguments and then return the flattened result. You can still get a count of the arguments if required but for this task, I don’t think you’ll need it.

function findInputGiven(...arrays) {
  // you can get the argument count if you need it
  console.log(`Got ${arrays.length} argument(s)`)

  // return the flattened result
  return arrays.flat()
}

console.info(findInputGiven([1, 2], [3, 4]))
console.info(findInputGiven([1, 2], [3, 4], [5, 6]))
.as-console-wrapper { max-height: 100% !important }
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement