我找到了以下布尔排序:
const sorted = things.sort((left, right) => {
return Number(!!left.current) - Number(!!right.current);
});
这是对布尔值排序的正确方法吗?
发布于 2018-05-29 15:47:27
您可以使用值的差异,转换为布尔值。
减号运算符将两个操作数强制为number,并返回一个反映Array#sort
所需顺序的数值。
undefined
值为are sorted to the end,从不用于排序回调。
var booleans = [0, true, 42, undefined, null, NaN, 'foo'];
booleans.sort((a, b) => Boolean(a) - Boolean(b)); // falsy values first
console.log(booleans);
booleans.sort((a, b) => Boolean(b) - Boolean(a)); // truthy values first
console.log(booleans);
.as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/50578957
复制相似问题