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

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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