I have a array of Object with mixed Alphanumeric. I need to sort the order by size.
var data = [
{size: "40 SHORT", avail: true},
{size: "46 LONG", avail: true},
{size: "42 SHORT", avail: true},
{size: "40 REG", avail: true},
{size: "42 LONG", avail: true},
{size: "42 REG", avail: true},
{size: "44 REG", avail: true},
{size: "44 LONG", avail: true},
{size: "46 REG", avail: true},
{size: "48 REG", avail: true},
{size: "44 SHORT", avail: true},
{size: "38 REG", avail: true},
{size: "40 LONG", avail: true},
{size: "48 LONG", avail: true},
{size: "38 SHORT", avail: true}
]
I need the output like this.
var Output = [
{size: "38 SHORT", avail: true},
{size: "40 SHORT", avail: true},
{size: "42 SHORT", avail: true},
{size: "44 SHORT", avail: true},
{size: "38 REG", avail: true},
{size: "40 REG", avail: true},
{size: "42 REG", avail: true},
{size: "44 REG", avail: true},
{size: "46 REG", avail: true},
{size: "48 REG", avail: true},
{size: "40 LONG", avail: true},
{size: "42 LONG", avail: true},
{size: "44 LONG", avail: true},
{size: "46 LONG", avail: true},
{size: "48 LONG", avail: true}
]
You could split the value and take a numerical value for the given size.
var data = [{ size: "40 SHORT", avail: true }, { size: "46 LONG", avail: true }, { size: "42 SHORT", avail: true }, { size: "40 REG", avail: true }, { size: "42 LONG", avail: true }, { size: "42 REG", avail: true }, { size: "44 REG", avail: true }, { size: "44 LONG", avail: true }, { size: "46 REG", avail: true }, { size: "48 REG", avail: true }, { size: "44 SHORT", avail: true }, { size: "38 REG", avail: true }, { size: "40 LONG", avail: true }, { size: "48 LONG", avail: true }, { size: "38 SHORT", avail: true }];
data.sort(function (a, b) {
function getParts(o) {
var array = o.size.split(' ');
return { value: array[0], size: { SHORT: 1, REG: 2, LONG: 3 }[array[1]] };
}
var aa = getParts(a),
bb = getParts(b);
return aa.size - bb.size || aa.value - bb.value;
});
console.log(data)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments