'How to sort serialized JS array?

I have such output from form with $("form").serializeArray():

Answers[0].Id: 16
Answers[0].AnswerText: Go to 2
Answers[0].AnswerLink: 2
Answers[3].Id: 23
Answers[3].AnswerText: Go to 4
Answers[3].AnswerLink: 4
Answers[7].Id: 28
Answers[7].AnswerText: Go to 3
Answers[7].AnswerLink: 3

Everything that is before : is name, after : is value How to convert it to sorted array, like:

Answers[0].Id: 16
Answers[0].AnswerText: Go to 2
Answers[0].AnswerLink: 2
Answers[1].Id: 23
Answers[1].AnswerText: Go to 4
Answers[1].AnswerLink: 4
Answers[2].Id: 28
Answers[2].AnswerText: Go to 3
Answers[2].AnswerLink: 3

with javascript / jQuery?



Solution 1:[1]

If you want to just normalize your indexes, then you could create new array and then do something like

const newArray = [];
serializedArray.forEach((item) => newArray.push(item));
return newArray;

Or, another way is to just pass it through an "always true" filter, like:

serializedArray.filter(()=>true);

Solution 2:[2]

It's pretty simple but it depends on how you want to use this data you feel? But I suppose you could run an array length and sort your checks some how.

function MyHugeFunction (data) {
  console.log(`Size: ${data.length}`);
  console.log(`First Arg: ${data[0]}`);
  console.log(`Entire Argument Set: ${data}`);
};

MyHugeFunction(["test","hello","123"]);

Solution 3:[3]

It's not obvious without the context but I think it is an exercise on spread operator.

In this case, your function would be something like

function(...args) {
  args.forEach((val) => console.log(val))
}

or

function(...args) {
  console.log(...args)
}

The "...args" is used to get all the arguments of your function in a "args array" and the forEach function applied to this array does the trick

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 xROOKH
Solution 2 BGPHiJACK
Solution 3 Matthieu Bouxin