Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda