-3

Input: 3X,LG,XL,4X Output: LG,XL,3X,4X

Input: LG,XL,2X,5X,2X Output: SM,MD,2X,2X,5X

I need to sort this array like this in the above Input-output I tried so many methods but not getting this output.

As per the given solution I need to solve the question.

2
  • 5
    Sort it how? May you share your "many methods" as minimal reproducible examples? Jun 24, 2021 at 15:50
  • What is the logic for sorting these? Are they clothe sizes? Something else?
    – VLAZ
    Jun 24, 2021 at 15:55

4 Answers 4

4

Define an order in advance using an array and use their positions to sort the sizes.

function sortBySize(toSort = []) {
  const ORDER = ['SM', 'MD', 'LG', 'XL', '2X', '3X', '4X', '5X'];

  return [...toSort].sort((a, b) => {
    const aIndex = ORDER.indexOf(a);
    const bIndex = ORDER.indexOf(b);

    return aIndex - bIndex;
  });
}
2
  • 1
    You could use ORDER.indexOf(a) instead of findIndex
    – adiga
    Jun 24, 2021 at 16:43
  • Great call @adiga – used to finding more complex things with the callback. Edited.
    – LMulvey
    Jun 24, 2021 at 16:50
2

The comparison between SM and LG can't be done with standard comparison functions. Nothing indicates to the computer that S is less then L. In order to compare them directly, we'll have to teach the computer what each item in the list means. You've got a couple ways of doing this:

  • Giving a weight to each possible option. For example: M = 0, S = -1, XS = -2 etc. Once you have this distinction set up, you can convert the array to it's integer values and sort that using standard sorting methods.
  • Specifying the list of options with their order and comparing against that. Something like @LMulvey's answer
2
  • "Nothing indicates to the computer that S is less then L." it's the comparison function you pass that should do that. Except for lexicographical sorting and very few others, there is no intrinsic way of saying "Sort it like this" without using a custom comparer. So, what the computer does or doesn't know is irrelevant. Most of the time it's us telling the computer what the comparison would be.
    – VLAZ
    Jun 24, 2021 at 16:02
  • @VLAZ Exactly what I was trying to express
    – Josh
    Jun 24, 2021 at 16:20
0

I'm assuming you want to sort strings of size labels (like for clothing) in order from smallest to largest, from "SM" (small) to some arbitrarily high XL size like "5X". The default Array.prototype.sort won't work for that purpose (it will sort your strings alphabetically instead).

To do this we need to create a sorting function that compares two sizes:

    const stdSizes = ['SM','MD','LG','XL'];
    function compareSizes(left, right) {
        const leftIsXL = left.slice(-1) == "X", rightIsXL = right.slice(-1) == "X";
        // compare two XL sizes, e.g., 2X vs 3X
        if (leftIsXL && rightIsXL) return parseInt(left) - parseInt(right);
        // compare one XL size to any other size
        else if (left.slice(-1) == "X") return 1;
        else if (right.slice(-1) == "X") return -1;
        // compare two non-XL sizes
        else return stdSizes.indexOf(left) - stdSizes.indexOf(right);
    }

Then pass it into .sort():

console.log(['3X','4X','2X','MD','SM','XL'].sort(compareSizes))

The output of this is:

Array(6) [ "SM", "MD", "XL", "2X", "3X", "4X" ]

Array.prototype.sort() is documented here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

0

Here's another way that uses the order as a template which we fill through a reduce() and remove the empties

let order = "SM,MD,2X,3X,4X,5X,LG,XL".split(","); // our example order
"3X,LG,XL,4X".split(',') // array-ify the input
  .reduce((b,a) => {b[order.indexOf(a)]=a; return b}, // fill the available slot in the accumulator
  [].fill('',0,order.length)) //... which was pre-populated with empty indexes from fill()
  .filter(e=>e) //filter out the empties

and it fits nicely on one line

let sizes = "3X,LG,XL,4X".split(',').reduce((b,a) => {b[order.indexOf(a)]=a; return b},[].fill('',0,order.length)).filter(e=>e)

it uses reduce to fill an array of available sizes in the order of the example order and then filters out the empties

let order = "SM,MD,2X,3X,4X,5X,LG,XL".split(",");
const sortSizes = (s) => {
return s.split(',').reduce((b,a) => {b[order.indexOf(a)]=a; return b},[].fill('',0,order.length)).filter(e=>e)
}

let input="3X,LG,XL,4X";
//Output: LG,XL,3X,4X
console.log(sortSizes(input));

input = "LG,XL,2X,5X,2X"
//Output: SM,MD,2X,2X,5X
console.log(sortSizes(input));

Not the answer you're looking for? Browse other questions tagged or ask your own question.