我想知道如何在自定义订单上排序数组,而不是按字母顺序排序。想象一下,你有这个数组/对象:
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"
}];
在这里我们有3种不同的类型:水果,蔬菜和糖果。现在我想对这个阵列进行排序,并确保所有水果都是第一个,糖果来自水果,蔬菜是最后的。每种类型都需要按字母顺序对其项目进行排序。我们将使用像sortArrayOnOrder ( ["fruit","candy","vegetable"], "name" );
这样的函数。所以基本上,你会在排序之后得到这个数组:
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"
}];
任何人都知道如何为此创建脚本?
答案 0 :(得分:20)
Cerberus代码的改进版本:
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);
});
答案 1 :(得分:3)
试试这个:
var sortOrder = ['fruit','candy','vegetable']; // Declare a array that defines the order of the elements to be sorted.
somethingToSort.sort(
function(a, b){ // Pass a function to the sort that takes 2 elements to compare
if(a.type == b.type){ // If the elements both have the same `type`,
return a.name.localeCompare(b.name); // Compare the elements by `name`.
}else{ // Otherwise,
return sortOrder.indexOf(a.type) - sortOrder.indexOf(b.type); // Substract indexes, If element `a` comes first in the array, the returned value will be negative, resulting in it being sorted before `b`, and vice versa.
}
}
);
此外,您的对象声明不正确。而不是:
{
type = "fruit",
name = "banana"
}, // etc
使用:
{
type: "fruit",
name: "banana"
}, // etc
因此,请将=
符号替换为:
。
答案 2 :(得分:0)
Array.sort接受一个排序函数,您可以在其中应用自定义排序逻辑。
答案 3 :(得分:0)
对于希望按自定义顺序对字符串数组进行简单排序的人,请尝试以下功能:
// sorting fn
const applyCustomOrder = (arr, desiredOrder) => {
const orderForIndexVals = desiredOrder.slice(0).reverse();
arr.sort((a, b) => {
const aIndex = -orderForIndexVals.indexOf(a);
const bIndex = -orderForIndexVals.indexOf(b);
return aIndex - bIndex;
});
}
// example use
const orderIWant = ['cat', 'elephant', 'dog'];
const arrayToSort = ['elephant', 'dog', 'cat'];
applyCustomOrder(arrayToSort, orderIWant);
这将按照指定的顺序对数组进行排序。此功能的两个样本输入/输出:
示例1:
const orderIWant = ['cat', 'elephant', 'dog']
const arrayToSort = ['mouse', 'elephant', 'dog', 'cat'];
applyCustomOrder(arrayToSort, orderIWant);
console.log(arrayToSort); // ["cat", "elephant", "dog", "mouse"]
示例2:
const orderIWant = ['cat', 'elephant', 'dog'];
const arrayToSort = ['mouse', 'elephant', 'rabbit', 'dog', 'cat'];
applyCustomOrder(arrayToSort, orderIWant);
console.log(arrayToSort); /* ["cat", "elephant", "dog", "mouse",
"rabbit"] */