I want to create a array of strings by appending, but it matters if the origin is an array or yet a string. Therefore I need to convert a string like "abc" to a string array.
if I use
Array.from()
it makes me something like this ["a","b","c"] but I want to have ["abc"];
Is there a easy way that takes an input like "abc" and at the same time ["a","abc"] I so that I can append later one one more string with push for example?
some constraints: I cannot create
let a = [];
because it is coming from extern. And sure, I can add some code to check what is its, but I search for a simple mechanism.
I think i need something like arr1.flat();
I'm not quite sure if I understand your question correctly, you want to either append the source to an existing array if it's a string or concatenate the source if it's already an array?
Have you tried typeof? See the MDN typeof docs
if (typeof origin === 'string') {
mylist.push(origin)
} else {
mylist = mylist.concat(origin)
}
EDIT: As per NiceBooks comment:
let str = new String('Hello, world')
typeof str // 'object'
(source)
Therefore, as they suggested the following might be better:
if (Array.isArray(origin)) {
mylist = mylist.concat(origin) // there are more cleaner ways, for starters this should be fine
} else {
mylist.push(origin)
}
Maybe this does what you want:
function strArr(base,s){
return !Array.isArray(base)?[base,s]:[...base,s];
}
let a="abc", arr=["one","two"];
console.log(strArr(a,"b"));
console.log(strArr(arr,"three"));
I changed my answer slightly. Now the input array base will not be changed anymore by the function.