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

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

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 Denunciar

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 Denunciar

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 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