27

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?

6
  • I think you may use split() to convert a string in to array of one element Jan 4, 2019 at 13:03
  • 6
    Why don't you want to use a type-check? That would typically be the idiomatic and maintainable way to do this.
    – shiftweave
    Jan 4, 2019 at 17:11
  • 1
    @shiftweave +1. As the current responses show, the ways around this simply hide the type-check underneath another call and shift into the code-monkeying realm (or make it so that the method must be called with a variable number of parameters). The type check is the most idiomatic solution.
    – Mike Hill
    Jan 4, 2019 at 21:16
  • 1
    Why can't you just (names instanceof Array ? names : [names]).map()?
    – Salman A
    Jan 4, 2019 at 22:06
  • 1
    @sschmeck Yes, in Javascript (and typescript) the idiomatic way to do this would be to check typeof names === 'object' && names instanceof Array. Typeof returns a set of string values corresponding to the basic JS types, and "instanceof" checks some prototypical inheritance stuff. These answers are neat one-liners for golfing, but it's more maintainable to just explicitly type-check rather than to get clever.
    – shiftweave
    Jan 7, 2019 at 17:19

5 Answers 5

32

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']

0
9

Short solution:

[names].flat()

If names is an array, it will be left as-is. Anything else will be converted to an array with one element.

Demo

Demo

This works because .flat() only flattens one level by default.

If names is not an array, [names] makes it an array with one element, and .flat() does nothing more because the array has no child arrays. If names is an array, [names] makes it an array with one child array, and .flat() brings the child array back up to be a parent array.

Alternative

This is more self-explanitory:

names instanceof Array ? names : [names]

This uses a simple ternary statement to do nothing to it if it is an array already or make it an array if it is not already.

1
  • 1
    This seems more easy than the top voted solution with concat and map.
    – Timo
    Aug 25, 2022 at 10:29
3

Why not just check if the input is an array or not using isArray()?

I made another solution using this approach, also I put a control inside the map() so this don't fail when the name argument is null or undefined.

const names = x => (Array.isArray(x) ? x : [x]).map(name => name && name.toUpperCase());

console.log(JSON.stringify( names(['Bart', 'Lisa']) ));
console.log(JSON.stringify( names('Homer') ));
console.log(JSON.stringify( names('') ));
console.log(JSON.stringify( names(null) ));
console.log(JSON.stringify( names([null]) ));
console.log(JSON.stringify( names([undefined, "Roger", "Bob", null]) ));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

2

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" ]
2

Maybe an maybe upcoming method of Array#flat would help in this case (works actually only in Chrome and FF).

const names = unknown => [unknown].flat().map(name => name.toUpperCase())

console.log(names(['Bart', 'Lisa']));
console.log(names('Homer'));

3
  • This answer is identical to the solution OP wants to improve, but using a different polyfill.
    – shiftweave
    Jan 4, 2019 at 16:35
  • 1
    @shiftweave I see at least two differences: (1) it already works natively in some implementations; (2) it arguably improves the syntax of OP’s code by sugaring Array.of. Jan 4, 2019 at 19:13
  • If names is an array, it will be left as-is. Anything else will be converted to an array with one element. Demo: i.stack.imgur.com/fHWwl.png
    – RedGuy11
    Jun 11, 2021 at 22:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.