Array Sort Custom Compare

From SwiftAPI

Jump to: navigation, search


Sort an array in-place with a custom comparison function. The example below sorts an array of strings by the length of each string (shortest to longest).

JavaScript

developer.mozilla.org

var a = ["first", "foobar", "foo", "last"];
a.sort(function(x, y) { 
  return x.length - y.length;
});
// a == ["foo", "last", "first", "foobar"]

PHP

bool usort ( array &$array , callable $value_compare_func )
$a = array("first", "foobar", "foo", "last");
function cmpLength($x, $y) {
  return strlen($x) - strlen($y);
}
usort($a, 'cmpLength');
// $a == array("foo", "last", "first", "foobar")

Ruby

a = ["first", "foobar", "foo", "last"]
 
a.sort! do |x, y|
  x.length <=> y.length
end
# a == ["foo", "last", "first", "foobar"]
Personal tools