如何按项类型对数组进行排序,其中字符串应该先出现,然后是浮点和整数,同时保持相同的类型优先级,不使用额外的数组



输入:

[7,"a","b",5, 0.1, "c", 0.5, 9, 1, "e", "m", 0.3, 8.5, 74, 89,"f","r",0.5 ,"x", "y", 4, 7]

输出:

["a", "b", "c", "e", "m", "f", "r", "x", "y", 0.1, 0.5, 0.3, 8.5, 0.5, 7, 5, 9, 1, 74, 89, 4, 7]

function sorter(arr) {
var arr1, arr2, arr3;
arr1 = [];
arr2 = [];
arr3 = [];
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] === "string") {
arr1.push(arr[i]);
} else if (typeof arr[i] === 'number' && !isNaN(arr[i])) {
if (Number.isInteger(arr[i])) {
arr3.push(arr[i]);
} else {
arr2.push(arr[i]);
}
}
}
return [...arr1, ...arr2, ...arr3];
}

一种基于单个sort比较器回调的方法。。。

function orderByItemTypeOnly(a, b) {
const precedences = {
'string': 1,
'float': 2,
'int': 3,
};
const getType = val =>
((typeof val === 'number') && Number.isFinite(val))
? Number.isInteger(val) && 'int' || 'float'
: (typeof val);
const aType = getType(a);
const bType = getType(b);
return (
(precedences[aType] || 4) - (precedences[bType] || 4)
);
}
console.log([
7, "a", "b", 5, 0.1, "c", 0.5, 9, 1, "e", "m",
0.3, 8.5, 74, 89, "f", "r", 0.5, "x", "y", 4, 7
].sort(orderByItemTypeOnly));
.as-console-wrapper { min-height: 100%!important; top: 0; }

也有可能不是用sort,而是用reduce方法来解决这个问题。。。

function collectAndShiftItemByType(list, item, idx, arr) {
if (list.length === 0) {
list.push([], [], [], []);
}
const typeListIndex = ((typeof item === 'number') && Number.isFinite(item))
? (Number.isInteger(item) && 2 || 1)
: (typeof item === 'string') ? 0 : 3;
// push into sub lists ... [0]string, [1]float, [2]integer, [3]unknown.
list[typeListIndex].push(item);
if (idx >= arr.length - 1) {
list = list[0]
.concat(list[1])
.concat(list[2])
.concat(list[3]);
}
return list;
}
console.log([
7, "a", "b", 5, 0.1, "c", 0.5, 9, 1, "e", "m",
0.3, 8.5, 74, 89, "f", "r", 0.5, "x", "y", 4, 7
].reduce(collectAndShiftItemByType, []));
.as-console-wrapper { min-height: 100%!important; top: 0; }

sort()方法与比较类型而非值的比较函数一起使用。

function sorter(arr) {
function type_index(val) {
const types = ["string", "float", "integer"];
let type;
if (typeof val == "string") {
type = "string";
} else if (typeof val == "number" && Number.isInteger(val)) {
type = "integer";
} else if (typeof val == "number" && !isNaN(val)) {
type = "float";
}
return types.indexOf(type);
}
return arr.sort((a, b) => type_index(a) - type_index(b));
}
console.log(sorter([7,"a","b",5, 0.1, "c", 0.5, 9, 1, "e", "m", 0.3, 8.5, 74, 89,"f","r",0.5 ,"x", "y", 4, 7]));

最新更新