Monday 21 October 2019

javascript - 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?


Answer




Improved version of Cerbrus' code:



var ordering = {}, // map for efficient lookup of sortIndex
sortOrder = ['fruit','candy','vegetable'];
for (var i=0; i ordering[sortOrder[i]] = i;

somethingToSort.sort( function(a, b) {
return (ordering[a.type] - ordering[b.type]) || a.name.localeCompare(b.name);
});


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...