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

130
Visualizações
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.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

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(', '));

about 4 years ago · Santiago Trujillo Relatório

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

about 4 years ago · Santiago Trujillo Relatório

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(', '));

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