0

I have JSON data that looks something like this:

{
"items":[
{"name":"Dondasch",
"tier":"Rare"
},
{"name":"Elight",
"tier":"Rare"
},
{"name":"Krak",
"tier":"Unique"
}
]
}

and I'm looking for a way to sort them by the "Tier: ???". I want to group all "items" that have the same value together, preferably in a way I define (As in, I can choose if the ones with "rare" or "unique" come first, rather than it being alphabetical. After I've sorted them, I need to be able to perform this code on them:

data.items.forEach(wynnitem => {
      const card = document.createElement('div');
      card.setAttribute('class', 'card');

      const h1 = document.createElement('h1');
      $(h1).hide();
      h1.textContent = wynnitem.name;
      if (wynnitem.tier == "Unique") {
        h1.setAttribute('class', 'unique');
      } else if (wynnitem.tier == "Rare") {
        h1.setAttribute('class', 'rare');
      } else if (wynnitem.tier == "Legendary") {
        h1.setAttribute('class', 'legendary');
      } else if (wynnitem.tier == "Mythic") {
        h1.setAttribute('class', 'mythic');
      }
      $(h1).fadeIn(1000);
}):

Any other questions I've found just give a way to sort them alphabetically, not by a certain value.

Dr Bracewell
  • 96
  • 1
  • 9
  • `"message": "SyntaxError: unexpected token: ':'",` – connexo Nov 03 '18 at 11:01
  • Instead of doing all those `if...else if...`, can't you just do `h1.className = wynnitem.tier.toLowerCase();`? Also your line `$(h1).hide();` can safely be deleted. – connexo Nov 03 '18 at 11:03
  • 1
    Possible duplicate of [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – Dexygen Nov 03 '18 at 11:09

3 Answers3

0

you can apply Array.prototype.sort method to items and give it a compareFn

items.sort(function(a, b) {
    if (a.tier < b.tier) {
        return -1;
    }

    if (a.tier > b.tier) {
        return 1;
    }

    return 0;
});
allyraza
  • 1,376
  • 11
  • 7
0

You would only need to define a ranking/priority table and sort by this criteria :

const orderRanks = {
  unique: 2,
  rare: 4,
  legendary: 42,
  mythic: 420
};

const items = /*your items array*/;
items.sort((lhsItem, rhsItem) => {
  const lhs = lhsItem.tier.toLowerCase();
  const rhs = rhsItem.tier.toLowerCase();
  return orderRanks[lhs] - orderRanks[rhs];
  /*
  == -> 0
  lhs < rhs -> negative
  lhs > rhs -> positive

  this works because it is simple numbers (not NaN nor limits)
  */
});
Vivick
  • 3,434
  • 2
  • 12
  • 25
0

Try this :

  var list = {
    "items":[
    {"name":"Dondasch",
    "tier":"Rare"
    },
    {"name":"Elight",
    "tier":"Rare"
    },
    {"name":"Krak",
    "tier":"Unique"
    }
    ]
    }

And then sort the data using

list.items.sort(function(a, b) { return a["tier"]-b["tier"]} || a["name"] - b["name"]);
user1455719
  • 1,045
  • 4
  • 15
  • 35