0

Given the following Javascript object:

 {
      //none represent no media query
      none: "foo",
      '@media(max-width:450px)': "foo",
      '@media(min-width:1200px)': "foo",
      '@media(min-width:768px)': "foo",
 }

How can I sort it into an object like this, which resemble the correct stylesheet?

 {
      //none represent no media query
      none: "foo",
      '@media(max-width:450px)': "foo",
      '@media(min-width:768px)': "foo",
      '@media(min-width:1200px)': "foo",
 }
John Winston
  • 1,260
  • 15
  • 30

1 Answers1

0

I used the answer linked by Masoud Tahmasebi and found the regex here.

parseInt("none".replace( /(^.+\D)(\d+)(\D.+$)/i,'$2')) will return NaN so I used isNaN() to let the none keys go first.

a = {
      '@media(max-width:450px)': "foo",
      '@media(min-width:1200px)': "foo",
      '@media(min-width:768px)': "foo",
        none: "foo",
 }

function compare(a,b){
    a = parseInt(a.replace( /(^.+\D)(\d+)(\D.+$)/i,'$2'));
    b = parseInt(b.replace( /(^.+\D)(\d+)(\D.+$)/i,'$2'));
    if(isNaN(a) || a < b) return -1;
    if(isNaN(b) || a > b) return 1;
    return 0;
}

const ordered = Object.keys(a).sort(compare).reduce(
  (obj, key) => { 
    obj[key] = a[key]; 
    return obj;
  }, 
  {}
);
Tom
  • 4,972
  • 3
  • 10
  • 28