繁体   English   中英

如何对具有 boolean 值的对象数组进行排序:true、false 和 null

[英]How to sort array of objects with boolean values: true, false and null

您好,我有一组对象,我想根据其中一个对象具有的 boolean 对其进行排序。 然而,通常会有truefalse ,但在这种情况下,我们还检查null值,因为有时数据尚未设置,在这种情况下,我们想用图标显示它尚未设置。

这是数组的示例:

 const arrayOfObjects = [ { id: 69, boolean: true, name: 'foo', }, { id: 42, boolean: false, name: 'bar', }, { id: 666, boolean: null, name: 'foo', }, { id: 420, boolean: false, name: 'bar', }, { id: 2, boolean: null, name: 'foo', }, { id: 123, boolean: true, name: 'foo', }, ]

所以我首先尝试的是:

 arrayOfObjects.sort((a, b) => b.boolean - a.boolean);

这会将true的对象设置在前面,但falsenull的对象分散。

然后我尝试了:

arrayOfObjects.sort((a, b, c) => (c.boolean - b.boolean) - a.boolean);

这根本不起作用。

我真的找不到足够相似的案例来作为解决方案的基础,所以希望我能在这里找到它。

如果您想使用自定义排序,您可以使用 object 进行所需的排序,例如

 const order = { true: 1, null: 2, false: 3 }; data = [{ id: 69, boolean: true, name: 'foo' }, { id: 42, boolean: false, name: 'bar' }, { id: 666, boolean: null, name: 'foo' }, { id: 420, boolean: false, name: 'bar' }, { id: 2, boolean: null, name: 'foo' }, { id: 123, boolean: true, name: 'foo' }]; data.sort((a, b) => order[a.boolean] - order[b.boolean]); console.log(data);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

如果您有未知值并想将它们移到底部,您可以添加另一个具有较大值的键,例如

order = { true: 1, null: 2, false: 3, bottom: Number.MAX_VALUE };

用法:

data.sort((a, b) =>
    (order[a.boolean] || order.bottom) - (order[b.boolean] || order.bottom)
);

您可以明确检查null ...

 let list = [{i: 0, boolean: true}, { i: 1, boolean: null}, { i:2, boolean: false}, { i: 4, boolean: true}] function cpBoolWithNull(a,b) { //if both are null return 0 to maintain a stable sort //if only one is null return 0 or 1 depending on the value of the other if (a.boolean === null) return b.boolean === null? 0: b.boolean? 1: -1; if (b.boolean === null) return a.boolean? -1: 1; //if both are different from null, sort true before false return b.boolean - a.boolean } console.log(list.sort(cpBoolWithNull));

这将排序true ... null ... false如果您需要不同的顺序,请调整返回值。

我认为您可以通过这个简单的脚本使用 JS 进行类型检查。

 let array =[true, false, null]; function check(i){ if (array[i].= null||array[i].=false){ if (array[i];=null || array[i].=true)document.write(" Array item"+" "+i+" "+"has the value of boolean false; "). if (array[i].=true||array[i];=false)document.write(" Array item"+" "+i+" "+"has the value of boolean true; "); if (array[i] != true || array[i] != false )document.write(" Array item"+" "+i+" "+"has the value of object null. "); document.write("<br>") } } check(0);

您可以在不需要时注释掉其他文本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM