0

There is a function that receives one argument from a query. If the query is only one item the input will be a string like for example "1". Otherwise if the query has two the argument will be an array like ["1", "2"].

I eventually need to work with an array to use it on a for each and work with the data. So i found this solution but i don't think is the best way to perform this.

//orderInput can be an string "1" or an array of strings ["1","2"]
const parseOrder = (orderInput) => {

    const array = [].concat(orderInput);
    array.forEach(odr => {
        // Here it does something
    });


    return order;
}

Dropen77
  • 75
  • 5
  • So are you asking how to _check_ if a value is an Array, or how to _make_ the value an Array if it isn’t? – Sebastian Simon Mar 04 '22 at 19:35
  • If the value isn't an array turn it into one of one position – Dropen77 Mar 04 '22 at 19:39
  • 1
    You may also be interested in [Rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), which would allow users to provide any number of arguments as individual strings, but allow you to treat those arguments as a single array. And [Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), which would allow consumers to provide those arguments from an array in cases where they have to build them dynamically. – StriplingWarrior Mar 04 '22 at 19:39
  • 1
    Question in the title - [Array.isArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) – James Mar 04 '22 at 19:39
  • And if it's not an array, you can turn it into an array with `orderInput = [orderInput];` – Barmar Mar 04 '22 at 20:22

0 Answers0