0

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();

8
  • What is the structure of your original input? Commented Feb 6, 2022 at 12:46
  • let a = []; a.push("abc"); is that what you want? Commented Feb 6, 2022 at 12:48
  • i don't see why you don't just use [string] instead of Array.from() Commented Feb 6, 2022 at 12:48
  • if you want to have controle over all entries you could do something like: array.reduce((array, entry) => [(array[0] ?? '') + entry], ''); Commented Feb 6, 2022 at 12:50
  • 1
    Lastly with simply concats at the same level you could do [array.join('')]. Good luck Commented Feb 6, 2022 at 12:57

2 Answers 2

2

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Using typeof isn't a 100% solution to check if a variable is a String (typeof of strings created through the String constructor is object). On the other hand Array.isArray(origin) is the best way to check if a variable is an Array.
@NiceBooks Interesting, I didn't know that. I'll look into it and add it to my answer. Thanks.
1

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.