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

162
Visualizações
create array of objects from an array of string ids with 1st object having first value with second, second with third and so on

I have an array of strings e.g. const array1 = ["124542", "112244", "112245", "112246"];

I want to create below results:

const array2 = [
  {
    "comparableId": "124542",
    "comparatorId": "112244"
  },
  {
    "comparableId": "112244",
    "comparatorId": "112245"
  },
  {
    "comparableId": "112245",
    "comparatorId": "112246"
  }
]

In this array2, 1st index value from array1 is with 2nd value, 2nd value with 3rd and 3rd with 4th and so on. This array1 is dynamic and can have just 1 value e.g. const array1 = ["124542"]; and can have any number of values.

I have tried using Ecma Script reduce and map methods.

const array2 = array1.map((value, index) => {
    return {
       comparableId: value,
       comparatorId: array1[index + 1] || '',
    };
});

Is there some other good way to do it ?

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

0

Using a for loop is probably the easiest here.

const array1 = ["124542", "112244", "112245", "112246"];


const transform = (array) => {
  const result = [];

  for (let i = 0; i === 0 || i < array.length - 1; ++i) {
    result.push({
      comparableId: array[i],
      comparatorId: array[i + 1] ?? "",
    })
  }
  
  return result;
};

console.log(transform(array1));
console.log(transform(["124542"]));

about 4 years ago · Juan Pablo Isaza Relatório

0

const array1 = ["124542", "112244", "112245", "112246"];

let array2 = [];

array1.map((item, index) =>{
  
  array2.push({comparableId: item, comparatorId: array1[index+1] || ""})
})
console.log(array2)

about 4 years ago · Juan Pablo Isaza Relatório

0

Fully declarative, no mutations solution.

const
  array1 = ["124542", "112244", "112245", "112246"],
  array2 = [...Array(Math.ceil(array1.length / 2))].map((_, i) =>
    ({comparableId: array1[i * 2], comparatorId: array1[i * 2 + 1] ?? ""})
  );

console.log(array2);

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