Suppose I had the following Javascript array. How to sort by length, then alphabetically. Assume the following array:
var array = ["a", "aaa", "bb", "bbb", "c"];
When sorting it should produce: a, c, bb, aaa, bbb. Thank you in advance!
You can sort by length first and then use localeCompare()to sort in alphabetical order.
localeCompare()
var array = ["a", "aaa", "bb", "bbb", "c"]; array.sort(function(a, b) { return a.length - b.length || a.localeCompare(b) }) console.log(array)
Sort by length first, then alphabetically using || operator for several criteria. However, in your case there will be a simple view.
var array = ["a", "aaa", "bb", "bbb", "c"]; array.sort(function(a, b) { return a.length - b.length || a.localeCompare(b); }); console.log(array);
or
var array =["c", "aa", "bb", "bbb", "b", "aaa", "a"]; array.sort(function(a, b) { return a.length - b.length || [a,b].sort()[0]===b; }); console.log(array);
: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort?v=example
Source: https://habr.com/ru/post/1679290/More articles:Angular Router Animation Sync Errors - angularOracle regexp_replace in full words - sqlIn Kotlin, how can I get around conflicts with inherited declarations when the enum class implements an interface? - enumsIBM MQ retrieves the topic name from a message in a subscription queue - cInheritance and the base constructor - inheritanceะะพะดะฟะพัะปะตะดะพะฒะฐัะตะปัะฝะพััั ะณะปะฐัะฝัั - algorithm3D workarounds with Unity and Clara.io? - unity3dMockMvc HttpMediaTypeNotSupportedException: Content type 'application / json' is not supported - jsonHow to expand a 3D rectangle to show more rectangles when you click on it? - javascriptSpring integration test with mockmvc throws org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application / json' is not supported - springAll Articles