-3

i have an array of objects which is shown below

 [
  0: {name: "CMT", priority: 2}
  1: {name: "CDR BILLING", priority: 1}
  2: {name: "POOL DATA", priority: 5}
  3: {name: "FFM", priority: 3}
  4: {name: "SMPP", priority: 6}
  5: {name: "OTC", priority: 4}
 ];

how to sort this array such that the elemet having priority 1 shoould be at 0 index.What i want to achieve is

  [
  0: {name: "CDR BILLING", priority: 1}
  1: {name: "CMT", priority: 2}
  2: {name: "FFM", priority: 3} .....and so on
  ];
Benson OO
  • 477
  • 5
  • 22

2 Answers2

2

You can use sort method

let list = [
 {name: "CMT", priority: 2},
 {name: "CDR BILLING", priority: 1},
 {name: "POOL DATA", priority: 5},
 {name: "FFM", priority: 3},
 {name: "SMPP", priority: 6},
 {name: "OTC", priority: 4}
 ];
 
let listCopy = [...list];
listCopy.sort(function (a, b) {
  return a.priority - b.priority;
});

console.log(listCopy);
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20
-1
[
   {name: "CMT", priority: 2},
   {name: "CDR BILLING", priority: 1},
   {name: "POOL DATA", priority: 5},
   {name: "FFM", priority: 3},
   {name: "SMPP", priority: 6},
   {name: "OTC", priority: 4}
 ].sort((a,b)=>a.priority-b.priority) //! edited
dismedia
  • 129
  • 7
  • 1
    Unfortunately this doesn't work. I tested it in chrome. the function inside `.sort` should return a number -- see Saurabh's answer above. – TKoL Dec 02 '19 at 13:20
  • 1
    youre right, it should return number. I will correct the answer. Anyway, funny thing: I tested it on firefox before, and it is worked ok. – dismedia Dec 02 '19 at 13:24
  • that's interesting, it works on firefox for me as well. I suspect the reasoning for that is that the javascript spec does not define what happens when the callback returns something other than a number, and firefox has chosen to implement sorting in that case as well. It's still technically within spec. – TKoL Dec 02 '19 at 13:28
  • and that tricked me, anyway thanks for pointing it out :) – dismedia Dec 02 '19 at 13:32