簡體   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