Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!