[英]ranking arbitrary array of objects
If I have an array like this 如果我有这样的数组
var cars=
[
{ 'title':'brand', 'value':'honda'}
{ 'title':'brand', 'value':'toyota'}
{ 'title':'color', 'value':'red'}
{ 'title':'color', 'value':'white'}
{ 'title':'year', 'value':'1995'}
{ 'title':'year', 'value':'2006'}
{ 'title':'year', 'value':'2007'}
]
How can I write a single function that would return element's rank. 我如何编写一个可以返回元素等级的函数。 So for this array, for elements with title "brand" it should return 0, for elements with title "color" should return 1 and so on. 因此,对于此数组,对于标题为“ brand”的元素,它应该返回0,对于标题为“ color”的元素,它应该返回1,依此类推。 It should not cache or use any mapping table but should determine the rank on flight, so any time you call 它不应缓存或使用任何映射表,但应确定飞行等级,因此您可以随时调用
getRank(cars[6]) == 2 //true for the last element
getRank(cars[0]) == 0 //true for the first element
getRank(cars[1]) == 0 //true for the second element
getRank(cars[3]) == 1 //true for the fourth element
Updated answer based on your further explanations 根据您的进一步解释更新了答案
Javascript Java脚本
var cars = [
{ 'title':'brand', 'value':'honda'},
{ 'title':'brand', 'value':'toyota'},
{ 'title':'color', 'value':'red'},
{ 'title':'color', 'value':'white'},
{ 'title':'year', 'value':'1995'},
{ 'title':'year', 'value':'2006'},
{ 'title':'year', 'value':'2007'}
];
function getRank(data, number) {
var ranks = {},
rank = 0;
data.forEach(function (entry) {
if (typeof ranks[entry.title] !== "number") {
ranks[entry.title] = rank;
rank += 1;
}
});
return ranks[data[number].title];
}
console.log(getRank(cars, 6));
console.log(getRank(cars, 0));
console.log(getRank(cars, 1));
console.log(getRank(cars, 3));
Output 输出量
2
0
0
1
If it's already ordered (it must be cause otherwise I would really not understand your problem) you could do something like the following 如果已经订购(必须是原因,否则我真的不会理解您的问题),您可以执行以下操作
var current_index = -1;
var current_title = "";
for (var i in arr) {
if (arr[i].title!=current_title) {
current_title = arr[i].title;
current_index++;
}
arr[i].rank = current_index;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.