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

175
Visualizações
How to iteratively build a string

I had a hypothetical question for you, so excuse the code. This question regards a past test that I took, and an answer that I couldn't figure out, so it's not "doing homework," just something to satisfy my own curiosity. Unfortunately, I did not save any of my code.

Let's suppose we have the following input:

const input = [
                 ["add", "Hello"],
                 ["add", ", how"],
                 ["add", "is it"],
                 ["add", "going today?"]
              ]

How would one go about getting the following output:

["Hello",
 "Hello, how",
 "Hello, how is it",
 "Hello, how is it going today?"]

I utilized an output array (output), looped through input, and on each iteration I pushed input[0][1] to output, and to no surprise I built up an array that's just input[0][i]. Very rough example:

const output = [];
for (let i = 0; i < input.length; i++ {
    output.push(input[0][i];
}
=> ["Hello", ", how", "is it", "going today?"]

I had a few thoughts about how to go, but unfortunately ran out of time. One thought was just to iterate through the 'output' array and try to += a string, and then loop over that string (while it's being built) pushing to a final array. The other way was some sort of string builder, which I couldn't figure out.

Apologies if this is simple, I'm still learning.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Uses Array.reduce, then slice the array based on current index of input, finally join the slices.

const input = [
                 ["add", "Hello"],
                 ["add", ", how"],
                 ["add", "is it"],
                 ["add", "going today?"]
              ]
console.log(
  input.reduce((pre, cur, index, itself) => {
    pre[index] = itself.slice(0, index + 1).map(item => item[1]).join(' ')
    // pre[index] = itself.slice(0, index + 1).filter(item => item[0] === 'add').map(item => item[1]).join(' ') // if assuming only join the action (verb) is 'add'
    return pre
  }, [])
)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do a simple loop and push string at each iteration

const input = [
  ["add", "Hello"],
  ["add", ", how"],
  ["add", "is it"],
  ["add", "going today?"]
]

function addStr(arr){
  let newArr = []
  let str = ""
  for(let i=0; i<arr.length; i++){
    str = str + arr[i][1]
    newArr.push(str)
  }
  return newArr
}

console.log(addStr(input))

about 4 years ago · Juan Pablo Isaza Relatório

0

Similar to the other answer using reduce, but a different implementation that I tend to prefer because it's a bit easier to debug IMO:

const input = [
  ["add", "Hello"],
  ["add", ", how"],
  ["add", "is it"],
  ["add", "going today?"]
]

input.map(([_first, second]) => second)
  .reduce(
    (agg, newStr) => ([
      ...agg,
      (agg[agg.length - 1] + " " + newStr).trim()
    ]),
    [""]
  )
  .slice(1)

This gets you pretty close, but only caveat is that there's an oddity where you don't have a space between Hello and ", how" which is a bit difficult to reconcile programatically.

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