Dynamicly add values to and sort Javascript Object
Lets say i have this array of movie directors:
var directors = ['Woody Allen', 'Woody Allen', 'Clint Eastwood', 'Quentin Tarantino', 'Robert Rodriguez', 'Woody Allen', 'Steven Soderberg', 'Robert Rodriguez, Quentin Tarantino' ];
A PHP print_r of the aray would look like this:
Array
(
[0] => Woody Allen
[1] => Woody Allen
[2] => Clint Eastwood
[3] => Quentin Tarantino
[4] => Robert Rodriguez
[5] => Woody Allen
[6] => Steven Soderberg
[7] => Robert Rodriguez, Quentin Tarantino
)
What i would like to do with it is to loop through the array and create a new associative array with the name as key and the number of times it appears in the array as value. Plus sort the array after value highest first, so that the end result would be like tihs:
Array
(
[Woody Allen] => 3
[Robert Rodriguez] => 2
[Quentin Tarantino] => 2
[Steven Soderberg] => 1
[Clint Eastwood] => 1
)
I'm no expert on javascript, but if i would do it in PHP i would do like thi开发者_StackOverflow社区s:
$directors = array();
foreach($dirs as $d){
$pos = strpos($d,",");
if($pos === false) {
if($directors[$d]){
$directors[$d] = $directors[$d]+1;
}else{
$directors[$d] = 1;
}
}else{
$da = explode(",",$d);
foreach($da as $d){
$d = trim($d);
if($directors[$d]){
$directors[$d] = $directors[$d]+1;
}else{
$directors[$d] = 1;
}
}
}
}
arsort($directors);
Tried lots of ways to do the same thing in JavaScript, but since associative arrays don't exist in the same way in JS i've had som problems to get it to work. My best try was this code, but it doesn't do what i want:
function add2array(a,v){
if(a[v] != null){
a[v] = a[v]+1;
}else{
a[v] = 1;
}
}
$.each(directors, function(k, v){
if(v.indexOf(",") != -1){
dirs = v.split(",");
$.each(dirs, function(k, v){
dtrim = $.trim(v);
console.log(dtrim);
add2array(r,dtrim);
});
}else{
add2array(r,v);
}
});
This makes one big JS-Object with directorname as key and count as value, but is their any way for me to sort that? or do i need to make an array of objects to do that. Would be really helpfull if anyone could help me solve this. I'm using jQuery as you can se so your solution can use that to.
associative arrays have no order, so you can't sort them. you'll have to make an array containing key:value pairs and then sort on the property of the item.
I solved it myself:
var r = {}, re = [];
function add2array(a,v){
if(a[v] != null){
a[v] = a[v]+1;
}else{
a[v] = 1;
}
}
$.each(directors, function(k, v){
if(v.indexOf(",") != -1){
dirs = v.split(",");
$.each(dirs, function(k, v){
dtrim = $.trim(v);
add2array(r,dtrim);
});
}else{
add2array(r,v);
}
});
for (var i in r) {
re.push({ name : i, count : r[i] });
}
function compare(a,b) {
if (a.count > b.count)
return -1;
if (a.count < b.count)
return 1;
return 0;
}
re.sort(compare);
it works great on a standalone page, but there must be some conflict with my other scripts cause i can't use it where i need it...
精彩评论