1

How to sort an array follow by this sequence sm,s,m,l,xl. For example, I have an array like var a = [xl,sm,s,m] then i want to rearrange array to sm,s,m,xl

4
  • stackoverflow.com/questions/7157590/… Commented Sep 18, 2017 at 6:13
  • Please provide full example with expected result ? Commented Sep 18, 2017 at 6:16
  • what is the logic behind this new re-arrangement? Commented Sep 18, 2017 at 6:18
  • what is sm? a size? Commented Sep 18, 2017 at 6:21

2 Answers 2

1

You could take an object with the values of the strings and their position for sorting.

var array = ['xl', 'sm', 's', 'm'],
    order = { sm: 1, s: 2, m: 3, xl: 4 };

array.sort(function (a, b) {
    return order[a] - order[b];
});


console.log(array);

Sign up to request clarification or add additional context in comments.

Comments

0

I dont sure I understand what you want but I think you want something like below:

var sortGuide = ["sm", "s", "m", "xl"];
var a = ["xl", "sm", "s", "m"];
a.sort((it1, it2) => sortGuide.indexOf(it1) - sortGuide.indexOf(it2));
console.log(a);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.