Free coupon for initial registration

Sort associative array based on key in ascending order

Contents [hide]

Output

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

Code examples


JavaScript

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

Perl

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

PHP

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

Python

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

Ruby

1
2
3
example_array = {1 => "January", 12 => "December", 3 => "March" }
sorted_array = Hash[ example_array.sort ]
sorted_array.each { |tuple| print([tuple[0].to_s, tuple[1].to_s].join(" => ")+"\n") }
Free coupon for initial registration