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. 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
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));
On jsfiddle
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.