-1

I have an array of object in response as a json like:

const arr = [{
    Mandatory: false,
    Question: 65,
    QuestionType: "E",
    YesNo: "n",
    type: "QuestionOutput"
  },
  {
    Mandatory: false,
    Question: 64,
    QuestionType: "H",
    YesNo: "n",
    type: "QuestionOutput"
  },
  {
    Mandatory: false,
    Question: 85,
    QuestionType: "S",
    YesNo: "n",
    type: "QuestionOutput"
  },
  {
    Mandatory: false,
    Question: 61,
    QuestionType: "F",
    YesNo: "",
    type: "QuestionOutput"
  },
  {
    Mandatory: true,
    Question: 60,
    QuestionType: "F",
    YesNo: "",
    type: "QuestionOutput"
  }
];

I want to sort this array in ascending order based on the property Question and put the sorted object array into another object array.

Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
Smith
  • 119
  • 1
  • 2
  • 15

1 Answers1

1

You can use Array.prototype.sort() with the syntax arr.sort(compareFunction), and notice that as the property value in your object is an integer you can sort:

  • ASC: arr.sort((a, b) => a.Question - b.Question)
  • DESC: arr.sort((a, b) => b.Question - a.Question)

Code:

const arr = [{Mandatory: false,Question: 65,QuestionType: "E",YesNo: "n",type: "QuestionOutput"},{Mandatory: false,Question: 64,QuestionType: "H",YesNo: "n",type: "QuestionOutput"},{Mandatory: false,Question: 85,QuestionType: "S",YesNo: "n",type: "QuestionOutput"},{Mandatory: false,Question: 61,QuestionType: "F",YesNo: "",type: "QuestionOutput"},{Mandatory: true,Question: 60,QuestionType: "F",YesNo: "",type: "QuestionOutput"}];

arr.sort((a, b) => a.Question - b.Question);
console.log('arr:', arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46