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

142
Visualizações
Pushing items to array in an interpolated order

I have an array of objects and I am trying to interpolate data in a new array.

This is the array, that might have two or more objects:

const param = [{
    sortType: "ascending",
    sortField: "id",
  },
  {
    sortType: "descending",
    sortField: "title",
  },
];


let sortFields = [];
let sortTypes = [];
let sortString = [];

//iterates the sort params
for (let p of param) {
  sortFields.push(p.sortField);
  sortTypes.push(p.sortType);
}

for (let st of sortTypes) {
  sortString.push(st === "ascending" ? "+" : "-");
  for (let sf of sortFields) {
    sortString.push(sf);
  }
}
console.log({
  sortString
})

What I intend to do is to have an array with the following output: ["+id","-title"]

At the moment I am stuck with two interpolated for loops that do something very different. I have tried labeling the loops and using the continue keyword in the inner loops, but is still gives me a very different output.

Any suggestion on how can I achieve this? Maybe lopping the two array separately and then creating a new loop that interpolates and joins the strings in the array?

Any help is appreciated!

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

0

You are looping too much. You could simply use the Array.prototype.map function:

param.map(el => (el.sortType === 'ascending' ? '+' : '-') + el.sortField)
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use Array#map to turn each entry into into the string you want.

If you are going over a loop and pushing items to an array, it's very likely that it can be done in a cleaner way using Array#map.

const param = [{
    sortType: "ascending",
    sortField: "id",
  },
  {
    sortType: "descending",
    sortField: "title",
  },
];

const sortString = param.map((p) => {
   return p.sortType === "ascending" ? `+${p.sortField}` : `-${p.sortField}`
 });
console.log({
  sortString
})

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