Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string parameter to an array of one element

I wrote a function which has to support two types of a paramter names for a list of values. Internally it deals with the parameter as an array.

A single name is given as string and multiples names are given as an array of strings.

// simplified example let doSome =  names => names.map(name => name.toUpperCase())  names(['Bart', 'Lisa']) // [ 'BART', 'LISA' ] names('Homer') // TypeError: names.map is not a function 

I found a solution using Array.of() in combination with flatten() which needs some babel configuration.

doSome = names => Array.of(names).flatten().map(name => name.toUpperCase()); 

Is there an idiomatic way in JavaScript to get an array without a type check?

like image 755
sschmeck Avatar asked Jan 04 '19 12:01

sschmeck


People also ask

How do I turn a string into an array of elements?

To join the array elements we use arr. join() method. This method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(,).

How do I convert a string to an array of one string?

Create an empty String Buffer object. Traverse through the elements of the String array using loop. In the loop, append each element of the array to the StringBuffer object using the append() method. Finally convert the StringBuffer object to string using the toString() method.

Can a string convert into an array?

We can convert a String to a character array using either a naive for loop or the toCharArray() method. To convert a string to a string array based on a delimeter, we can use String. split() or Pattern. split() methods.


2 Answers

You can use Array.concat(), since concat accepts both arrays and non arrays:

const names = (v) => [].concat(v).map(name => name.toUpperCase())    console.log(names(['Bart', 'Lisa'])) // [ 'BART', 'LISA' ]  console.log(names('Homer')) // ['HOMER']
like image 81
Ori Drori Avatar answered Sep 22 '22 14:09

Ori Drori


You might not be able to implement it this way if you already have code depending on this function. Still, it would probably be cleaner to allow your function to accept a variable number of arguments with rest parameters.

It means you can call the function as names('Homer') or names('Bart', 'Lisa'):

function names(...args){    return args.map(name => name.toUpperCase());  }    console.log(names('Bart', 'Lisa')); // [ 'BART', 'LISA' ]  console.log(names('Homer')); // ['HOMER']

If you really want to call the function with an array as argument, you can use the spread syntax :

console.log(names(...['Bart', 'Lisa'])); // [ "BART", "LISA" ] 

If you use it with a string, you'll get back an array of characters, though:

console.log(names(...'Homer')); // [ "H", "O", "M", "E", "R" ] 
like image 23
Eric Duminil Avatar answered Sep 18 '22 14:09

Eric Duminil