根据值以降序对关联数组进行排序

Contents

输出结果

December => 12
March => 3
January => 1

程式码


JavaScript

const example_array = {"January":1, "December":12, "March":3};
var keys=[];
for(var key in example_array) {
  keys.push(key);
}
keys.sort((a,b)=>{return example_array[b]-example_array[a];});
for(var key of keys) {
  console.log(key + " => " + example_array[key] );
}

Perl

use strict;
my $example_array = {'January' => 1, 'December' => 12, 'March' => 3 };
foreach my $key (reverse sort {$example_array->{$a} <=> $example_array->{$b}} keys %{$example_array}) {
   print $key. " => " . $example_array->{$key} ."\n";
}

PHP

<?php
$example_array = ['January' => 1, 'December' => 12, 'March' => 3];
arsort($example_array);
foreach ($example_array as $key => $value) {
  echo $key . " => " . $value . "\n"; 
}

Python

example_array = {"January":1, "December":12, "March":3 }
tuples_sorted_by_key = sorted(example_array.items(), key=lambda x:x[1])[::-1]
for key, value in tuples_sorted_by_key:
  print(key + " => " + str(value))

Ruby

example_array = {"January" => 1, "December" => 12, "March" => 3 }
sorted_array = Hash[ example_array.sort_by{ |_, v| -v } ]
sorted_array.each { |tuple| print([tuple[0].to_s, tuple[1].to_s].join(" => ")+"\n") }