Sunday, January 22, 2012

Javascript: Sorting complex object (e.g. with S, M, L, XL sizes for clothing)

        var sorted_size_chart = ["XS", "S", "M", "L", "XL", "XXL", "STD"];
                
        // sort the array
        data.sort(function(a, b) {
            var a_size_index = a["size"];
            if (a["size"] && $.inArray(a["size"].toUpperCase(), sorted_size_chart) > -1) {
                a_size_index = $.inArray(a["size"].toUpperCase(), sorted_size_chart);
            }

            var b_size_index = b["size"];
            if (b["size"] && $.inArray(b["size"].toUpperCase(), sorted_size_chart) > -1) {
                b_size_index = $.inArray(b["size"].toUpperCase(), sorted_size_chart);
            }
            return a_size_index - b_size_index;
        });