2013-11-24 34 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