2017-01-19 89 views
0

時,我有一個數組:忽略「」排序對象數組

var array = { 
"mylist": [ 
    { 
     "item1": "The Ba", 
     "id": 1 
    }, 
    { 
     "item1": "Hurts Ama", 
     "id": 2 
    } 
    ] 
} 

,我使用下面的函數來對它們進行排序:

function sortByItem(a,b) { 
if (a.item1 < b.item1) 
    return -1; 
if (a.item1 > b.item1) 
    return 1; 
return 0; 
} 

這給了我輸出

[Hurts Ama, The Ba] 

但是,我不想在比較時包含「The」,以便輸出實際上是:

[Ba, Hurts Ama] 
+2

運行排序那一個對象,而不是陣列。你有一個數組作爲鍵mylist的值 – Moose

+0

我想最初的數組是'[Ba,Hurts Ama]',否則當前輸出與提出的對象不同 – RomanPerekhrest

+0

除了@所指出的問題外,穆斯,你的變量'數組'不僅僅是一個數組,它是一個隱式的全局數組。不要忘記'var'。 –

回答

2

您可以用下面的空格替換the

var array = [{ item1: "The Ba", id: 1 }, { item1: "Hurts Ama", id: 2 }, { item1: "Thereafter ", id: 3 }]; 
 

 
array.sort(function (a, b) { 
 
    function getStripped(s) { return s.replace(/^the\s+/i, ''); } 
 

 
    return getStripped(a.item1).localeCompare(getStripped(b.item1)); 
 
}); 
 

 
console.log(array)
.as-console-wrapper { max-height: 100% !important; top: 0; }

+1

最初的對象有鍵'「item1」'和'「item2」',而不是''item「' – RomanPerekhrest

+1

@NinaScholz漂亮的解決方案。完美工作。非常感謝你,祝你有美好的一天。 – helpisgood

-1

第一地圖的轉換函數每你的對象的,其去除任何「該」隨後通過

function transform(item) { 
    return { 
     id: item.id, 
     item: item.replace("The ","") 
    } 
} 

var list = 
[ 
    { 
     "item": "The Ba", 
     "id": 1 
    }, 
    { 
     "item": "Hurts Ama", 
     "id": 2 
    } 
] 
list.map(transform).sort(sortByItem)