Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda