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

137
Vistas
How to apply join only for particular section of an array?

I'm getting an array and strigifying it in this array variable:

let arrayStr = oldArr.join(', ');

My array looks like this in console:

(a), text1, (b), text2, (c), text3, (d), text3

What I want is to make it look like this:

(a) - text1, (b) - text2, (c) - text3, (d) - text3

I know that I've added ', ' after all strings, but how can I apply it like above?

Thanks.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can achieve this by looping through the array and accessing the current item and also the following one by its index and then appending both to the same element of a new array, something like this:

var oldArr = ['(a)', 'text1', '(b)', 'text2', '(c)', 'text3', '(d)', 'text3'];

var newArr = [];
for (var i = 0; i < oldArr.length; i++) {
  newArr.push(oldArr[i] + ' - ' + oldArr[++i]);
}

console.log(newArr.join(', '));

over 4 years ago · Santiago Trujillo Denunciar

0

You could use a three step solution, first get all items who are connected in a single sub array, map the joinded sub arrays and joun the outer array.

var array = ['(a)', 'text1', '(b)', 'text2', '(c)', 'text3', '(d)', 'text3'],
    text = array
        .reduce(function (r, a, i) {
            i % 2 ? r[r.length - 1].push(a) : r.push([a]) ;
            return r;
        }, [])
        .map(function (a) {
            return a.join(' - ');
        })
        .join(', ');

console.log(text);

over 4 years ago · Santiago Trujillo Denunciar

0

You can loop through all the array elements and make use of %(modulo) operator to combine the values as you need:

var oldArr = ['(a)', 'text1', '(b)', 'text2', '(c)', 'text3', '(d)', 'text4'];
var arrayStr  = [];
for (var i = 0; i < oldArr.length; i++) {
  if (i % 2 != 0) {
    oldArr[i] = oldArr[i - 1] + ' - ' + oldArr[i] ;
    arrayStr.push(oldArr[i]);
  }
}
console.log(arrayStr.join(', '));

over 4 years ago · Santiago Trujillo 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