1

I have this JSON data, not sure how to call it because the JavaScript objects vs JavaScript arrays vs JSON strings confuse me a lot.

     {  'slot': 1, url: 'http://example.com'},
     {  'slot': 2, url: 'http://example.com'},
     {  'slot': 3, url: 'http://example.com'},
     {  'slot': 1, url: 'http://example.com'},
     {  'slot': 2, url: 'http://example.com'},
     {  'slot': 3, url: 'http://example.com'},
     {  'slot': 4, url: 'http://example.com'},

Is there an easy way to sort it by my slot value so that it becomes like this: ?

     {  'slot': 1, url: 'http://example.com'},
     {  'slot': 1, url: 'http://example.com'},
     {  'slot': 2, url: 'http://example.com'},
     {  'slot': 2, url: 'http://example.com'},
     {  'slot': 3, url: 'http://example.com'},
     {  'slot': 3, url: 'http://example.com'},
     {  'slot': 4, url: 'http://example.com'},

I can probably do it by looping and creating a copy of the object/array but maybe there are some predefined sort() functions for this ?

adrianTNT
  • 3,671
  • 5
  • 29
  • 35

2 Answers2

2
    let ToSort = [
  { slot: 1, url: "http://example.com" },
  { slot: 2, url: "http://example.com" },
  { slot: 3, url: "http://example.com" },
  { slot: 1, url: "http://example.com" },
  { slot: 2, url: "http://example.com" },
  { slot: 3, url: "http://example.com" },
  { slot: 4, url: "http://example.com" },
];

 ToSort.sort(function(a, b){
   return a.slot - b .slot
 })
 console.log(ToSort)
Khant
  • 958
  • 5
  • 20
1

Below snippet should help you

const data = [
  { slot: 1, url: "http://example.com" },
  { slot: 2, url: "http://example.com" },
  { slot: 3, url: "http://example.com" },
  { slot: 1, url: "http://example.com" },
  { slot: 2, url: "http://example.com" },
  { slot: 3, url: "http://example.com" },
  { slot: 4, url: "http://example.com" },
]

function compare(a, b) {
  if (a.slot < b.slot) {
    return -1
  }
  if (a.slot > b.slot) {
    return 1
  }
  return 0
}

data.sort(compare)

console.log(data)
hgb123
  • 13,869
  • 3
  • 20
  • 38