Home > Blockchain >  Pushing items to array in an interpolated order
Pushing items to array in an interpolated order

Time:06-02

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!

CodePudding user response:

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

CodePudding user response:

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

param.map(el => (el.sortType === 'ascending' ? ' ' : '-')   el.sortField)
  • Related