2013-11-24 31 views
1

行,所以給這個輸入(其他屬性都被剝奪了簡潔):在JavaScript中的數組索引中排序對象?

var names = [{ 
    name: 'Michael' 
}, { 
    name: 'Liam' 
}, { 
    name: 'Jake' 
}, { 
    name: 'Dave' 
}, { 
    name: 'Adam' 
}]; 

我想用另一個數組的索引對它們進行排序,如果他們不是數組中,按字母順序排序。

var list = ['Jake', 'Michael', 'Liam']; 

給予我的輸出:

Jake, Michael, Liam, Adam, Dave 

我一直在使用LO-破折號嘗試,但它並不完全正確:

names = _.sortBy(names, 'name'); 
names = _.sortBy(names, function(name) { 
    var index = _.indexOf(list, name.name); 
    return (index === -1) ? -index : 0; 
}); 

的輸出是:

Jake, Liam, Michael, Adam, Dave 

任何幫助將非常感激!

+0

爲什麼'Adam'然後'Dave',你怎麼樣說出來? – elclanrs

+0

我希望您知道在javascript中有一個名爲sort()的函數,它可以按字母順序排列數組!所以現在的問題是將你的元素移動到另一個數組中? list.sort(); 將輸出 Adam,Dave,Jake,Michael,Liam – ProllyGeek

+0

@elclanrs - 「如果它們不在該數組中,按字母順序排序」,則換句話說,整個數組按字母順序排序,但如果說得通。是的,我知道'sort()',儘管我已經在項目中使用了lodash,所以對我來說使用本地方法並不重要(在我看來,整潔)。 – Ben

回答

3

你就近了。 return (index === -1) ? -index : 0;是問題所在。

按照你的方法,它應該是這樣的:

names = _.sortBy(names, 'name') 

var listLength = list.length; 

_.sortBy(names, function(name) { 
    var index = _.indexOf(list, name.name); 
    // If the name is not in `list`, put it at the end 
    // (`listLength` is greater than any index in the `list`). 
    // Otherwise, return the `index` so the order matches the list. 
    return (index === -1) ? listLength : index; 
}); 
+0

工程很棒。謝謝你的解釋。 :-) – Ben