Answers for "array sort by key"

PHP
10

php sort array by key

$weight = [
    'Pete' => 75, 
    'Benjamin' => 89,
    'Jonathan' => 101
  ];  	
  ksort($weight);
Posted by: Guest on December-04-2019
3

array sort by key javascript

function sortByKey(array, key) {
  return array.sort((a, b) => {
    let x = a[key];
    let y = b[key];
    
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
  });
}
Posted by: Guest on April-10-2020
2

php sort array of array by key

$inventory = [
	['price' => 10.99, 'product' => 'foo 1'],
    ['price' => 5.99, 'product' => 'foo 2'],
  	['price' => 100, 'product' => 'foo 3'],
  
];

$price = array_column($inventory, 'price');

array_multisort($price, SORT_DESC, $inventory);
Posted by: Guest on August-25-2020

Browse Popular Code Answers by Language