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

149
Visualizações
How to get array elements in sets of 2, without a traditional for loop

I have an array with 1000 random, fake addresses. But each address is split into 2 different arrays. for example:

[['123 main street'], ['San Diego, CA, 92101'],['22 washington ave'],['Miami, FL, 56624']]

My goal is to either mutate the current array or just create a new array with the following:

[['123 main street, San Diego, CA, 92101'],['22 washington ave, Miami, FL, 56624']]

I want to do this without using the traditional- for(let i = 1....).

I currently have the following:

const addressesFinal = addressesBad
  .map(function (cur, i, arr) {
    return [arr[i], arr[i + 1]];
  })
  .filter((e, i) => i % 2 === 0);

Is there an easier, cleaner way to do this? I'd like to use a modern array method besides a for loop and push.

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

0

It's a good case for reduce. On even indexes, push the array from the input. On odd indexes, add the element to the last array...

const array = [['123 main street'], ['San Diego, CA, 92101'],['22 washington ave'],['Miami, FL, 56624']]

const addresses = array.reduce((acc, el, index) => {
  return index % 2 ? acc[acc.length-1].push(el[0]) : acc.push(el), acc;
}, []);

console.log(addresses)

about 4 years ago · Santiago Trujillo Relatório

0

Here you go (All the descriptive comments added in the below code snippet itself) :

// Input array
const arr = [['123 main street'], ['San Diego, CA, 92101'],['22 washington ave'],['Miami, FL, 56624']];

// Declare a variable to push the final result.
const res = [];

// iterating an array to do the manipulation in data.
arr.forEach((item, index) => {
    // concat the array items (index with (index + 1))
    arr[item] = item.concat(arr[index + 1])
    // Splicing the alternate index element.
    arr.splice(index + 1, 1);
    // join the array elements.
    arr[item] = [arr[item].join()];
    // pushing the final items in the res array.
    res.push(arr[item]);
});

// output
console.log(res);

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