簡體   English   中英

按屬性對對象數組進行排序(使用自定義順序,不按字母順序)

[英]Sort an array of object by a property (with custom order, not alphabetically)

我想就這個小問題得到你的幫助。

我想根據代碼而不是按字母順序來排序這個數組。 我用粗體指定了這個,但最終還是被標記了,人們甚至不關心閱讀這個問題

例如,我想要所有綠色對象,然后是所有藍色對象,然后是所有紅色對象。 最好的方法是什么?

[
    { code: "RED", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0}
]

是否可以使用排序功能來做到這一點? 在那種情況下會是什么條件?

您可以為想要的訂單拿一個對象。

 var array = [{ code: "RED", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }], order = { GREEN: 1, BLUE: 2, RED: 3 }; array.sort(function (a, b) { return order[a.code] - order[b.code]; }); console.log(array);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

對於未知的顏色/值,您可以使用默認值

  • 0 ,用於排序到頂部或
  • Infinity大或正如某些人所建議的那樣,因為能夠計算Number.MAX_VALUE以排序到最后,
  • 或用於在其他組之間進行排序的任何其他值。

最后,您可以使用其他排序部分對特殊處理的項目進行排序,並用邏輯 OR ||鏈接。 .

 var array = [{ code: "YELLOW", value: 0 }, { code: "BLACK", value: 0 }, { code: "RED", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }], order = { GREEN: 1, BLUE: 2, RED: 3, default: Infinity }; array.sort(function (a, b) { return (order[a.code] || order.default) - (order[b.code] || order.default) || a.code.localeCompare(b.code); }); console.log(array);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

先設置自定義優先級

var codePriority = [ "GREEN", "BLUE", "RED" ];

現在在排序中使用相同的

arr.sort( function(a,b){ 
   if ( a.code == b.code ) return a.value - b.value;
   return codePriority.indexOf( a.code ) - codePriority.indexOf( b.code ) ; notice this line
})

演示

 var arr = [ { code: "RED", value: 0}, { code: "BLUE", value: 0}, { code: "RED", value: 0}, { code: "GREEN", value: 0}, { code: "BLUE", value: 0}, { code: "RED", value: 0}, { code: "GREEN", value: 0}, { code: "BLUE", value: 0} ]; var codePriority = [ "GREEN", "BLUE", "RED" ]; arr.sort( function(a,b){ if ( a.code == b.code ) return a.value - b.value; return codePriority.indexOf( a.code ) - codePriority.indexOf( b.code ) }); console.log( arr );

您可以實現一個模式數組並根據該模式數組中元素的索引進行排序。

 const a = ['GREEN', 'BLUE', 'RED']; const o = [{code:"RED",value:0},{code:"BLUE",value:0},{code:"RED",value:0},{code:"GREEN",value:0},{code:"BLUE",value:0},{code:"RED",value:0},{code:"GREEN",value:0},{code:"BLUE",value:0}]; const r = o.slice().sort(({ code: q }, { code: w }) => a.indexOf(q) - a.indexOf(w)); console.log(r);

這是一個按特定顏色排序的功能。

 const colors = [{ name: "T-shirt", color: "red", price: 20 }, { name: "Shoes", color: "yellow", price: 20 }, { name: "Pants", color: "red", price: 20 }, { name: "Cap", color: "yellow", price: 20 }, { name: "Skirt", color: "red", price: 15 }, ] let sortByColor = color => colors.sort((a, b) => a.color === color ? -1 : 1) console.log(sortByColor('red'))

您可以使用排序函數即 Array.prototype.sort() 訪問https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

首先,您必須決定是要按升序還是降序排序。 要按升序排序,您可以執行以下操作:

arr.sort((a, b) => {
    return a.color < b.color ? -1 : a.color > b.color ? 1 : 0;
  });

按降序執行:

arr.sort((a, b) => {
    return a.color > b.color ? -1 : a.color < b.color ? 1 : 0;
  });

現在假設您希望首先對某種顏色進行排序和顯示。 你可以有這樣的功能:

const sortByKeyAsc = (arr,color) =>
  arr.sort((a, b) => {
    if(a.color < b.color || (a.color === color && b.color !== color)){
      return -1;
    }
    if(a.color > b.color || (a.color !== color && b.color === color)){
      return 1
    }
    return 0;
  });

你可以像這樣使用它:

const array1 = sortByKeyAsc(arr,'pink');

我正在處理一個必須匹配字符串狀態並專門按各種狀態排序的情況。 .findIndex.includes最終成為最好的方法。

statusPriority 設置預期的順序。 一旦找到索引,就可以將它們進行比較並返回給 .sort

 let records = [ {status: 'Record is ready to submit.', active: true, name: 'A'}, {status: 'Record has been sent.', active: true, name: 'B'}, {status: 'Activation is required.', active: true, name: 'C'}, {status: 'Record submission failed.', active: true, name: 'D'}, {status: 'Creation is pending.', active: true, name: 'E'}, ] console.log(records.map(r => r.status)) let statusPriority = ['creation', 'activation', 'sent', 'ready', 'failed']; records.sort((a, b) => { let aIndex = statusPriority.findIndex(status => a.status.toLowerCase().includes(status)); let bIndex = statusPriority.findIndex(status => b.status.toLowerCase().includes(status)); return aIndex - bIndex; }) console.log(records.map(r => r.status))

您可以使用此功能按字母順序對顏色進行排序

  var sortedArr = arr.sort((first, second)=>{
            
        return first.color < second.color ? -1 : 1
    })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM