Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting on a custom order

I was wondering how I can sort an array on a custom order, not alphabetical. Imagine you have this array/object:

var somethingToSort = [{     type: "fruit",     name: "banana" }, {     type: "candy",     name: "twix" }, {     type: "vegetable",     name: "broccoli" }, {     type: "vegetable",     name: "carrot" }, {     type: "fruit",     name: "strawberry" }, {     type: "candy",     name: "kitkat" }, {     type: "fruit",     name: "apple" }]; 

In here we have 3 different types: fruit, vegetable and candy. Now I want to sort this array, and make sure that all fruits are first, candies come after fruits, and vegetables be last. Each type need their items to be sorted on alphabetical order. We will use a function like sortArrayOnOrder ( ["fruit","candy","vegetable"], "name" ); So basically, you would end up with this array after sorting:

var somethingToSort = [{     type: "fruit",     name: "apple" }, {     type: "fruit",     name: "banana" }, {     type: "fruit",     name: "strawberry" }, {     type: "candy",     name: "kitkat" }, {     type: "candy",     name: "twix" }, {     type: "vegetable",     name: "broccoli" }, {     type: "vegetable",     name: "carrot" }]; 

Anyone an idea how to create a script for this?

like image 423
Deltanic Avatar asked Feb 14 '13 10:02

Deltanic


People also ask

How do you sort a list in custom order in Python?

Using sort(), lamba, index(): The sort() function does the required in-place sorting(without creating a separate list to store the sorted order) along with a lambda function with a key to specify the function execution for each pair of tuples, the index() function helps to get the order from our custom list list_2.

What is custom sorting give one example?

For example, the string values 22 and 33 will be sorted into the order 22 , 33 , but if the values are 22 and 3 , the sort order will be 22 , 3 , because the character 2 comes before the character 3 in a lexicographical sort and representations of numbers with positional digits are not recognized.

What is custom sort order in Excel?

Custom Sorting in MS Excel Custom Sort allows you to create your order in which you want to sort the data. Sometimes you do not prefer the existing order and you want to sort it in a different order, then you can always choose to Custom Sort your data. To do Custom Sorting, you just need to create a Custom List.


1 Answers

Improved version of Cerbrus' code:

var ordering = {}, // map for efficient lookup of sortIndex     sortOrder = ['fruit','candy','vegetable']; for (var i=0; i<sortOrder.length; i++)     ordering[sortOrder[i]] = i;  somethingToSort.sort( function(a, b) {     return (ordering[a.type] - ordering[b.type]) || a.name.localeCompare(b.name); }); 
like image 100
Bergi Avatar answered Oct 03 '22 09:10

Bergi