Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
append string to string array if not array yet

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)
}
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!