Chad Sorting JS

April 7, 2021tip slipsjavascript

Sort JSON Like a Jesus Sharing a Bread as His Body

I always wonder how would I sort my Objects based on keys if the data structured in a nested Objects. I want it to be returning a sorted Object itself instead of just a value, e.g:

{
    buttPlug: {
        price: 20,
        discount: 4
    },
    dildo: {
        price: 60,
        discount: 8
    },
    whip: {
        price: 35,
        discount: 2
    },
    vibrator: {
        price: 10,
        discount: 0
    }
}
  • What if I want to sort them by name descendingly? like "whip -> vibrator -> …" with persisting the same data in each?
  • What about if I want to sort them by price from highest to lowest but still giving me the whole objects sorted instead of just its value?

Now with the power of Stackoverflow combined with this ass silly brain, I made a sexgod algorithm to sort all of those in a cool way as the boomer thought when they went to factory for first time.

Solution

/*
 *   data/object/json sorted in a sense of
 *   {
 *       x: {a: value, a: value, a: value},
 *       y: {b: value, b: value, b: value}
 *   }
 */

const chadSort = (data, sortingField, sortingDirection) => {

    let sortby = "";

    if (sortingField === "CATEGORY") {
        sortby = "category";
    } else if (sortingField === "PRICE") {
        sortby = "price";
    } else if (sortingField === "DISCOUNT") {
        sortby = "discount";
    }

    const sortedData = Object.entries(data)
        .sort(([y, { [sortby]: b }], [x, { [sortby]: a }]) => {
            if (sortingDirection === "ascending") {
                if (sortby === "category") {
                    return y < x ? -1 : y > x ? 1 : 0;
                } else {
                    return a - b;
                }
            } else if (sortingDirection === "descending") {
                if (sortby === "category") {
                    return y < x ? 1 : y > x ? -1 : 0;
                } else {
                    return b - a;
                }
            }
        })
        .reduce((r, [k, v]) => ({ ...r, [k]: v }), {});

    return sortedData;
}

RESULT

now if you call chadSort(data, "CATEGORY", "descending") will return ⬇️

{
    whip: {
        price: 35,
        discount: 2
    },
    vibrator: {
        price: 10,
        discount: 0
    },
    dildo: {
        price: 60,
        discount: 8
    },
    buttPlug: {
        price: 20,
        discount: 4
    }
}    

or if you call chadSort(data, "PRICE", "ascending") will return ⬇️

{
    dildo: {
        price: 60,
        discount: 8
    },
    whip: {
        price: 35,
        discount: 2
    },
    buttPlug: {
        price: 20,
        discount:4
    },
    vibrator: {
        price: 10,
        discount: 0
    }
}

NOTE

Btw make sure you use ES6 or higher, don't be virgin trying this on javascript version which still struggling hard compiting with Adobe Flash