sort function code example

Example 1: sort in descending order c++ stl

sort(arr, arr + n, greater<int>())

Example 2: javascript orderby

var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// sort by value
items.sort(function (a, b) {
  return a.value - b.value;
});

// sort by name
items.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});

Example 3: c++ sort

int arr[]= {2,3,5,6,1,2,3,6,10,100,200,0,-10};
    int n = sizeof(arr)/sizeof(int);  
    sort(arr,arr+n);

    for(int i: arr)
    {
        cout << i << " ";
    }

Example 4: how the sort function works javascript

const unsorted = ['d', 'd', 'h', 'r', 'v', 'z', 'f', 'c', 'g'];
const sorted = unsorted.sort();

console.log(sorted);
//["c", "d", "d", "f", "g", "h", "r", "v", "z"]


const unsortedNums = [45, 56, 3, 3, 4, 6, 7, 45, 1];
const sortedNums = unsortedNums.sort((a, b) => {
	return a - b;
});

console.log(sortedNums);
//[1, 3, 3, 4, 6, 7, 45, 45, 56]

Example 5: javascript sort object

var maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 28800
};
var sortable = [];
for (var vehicle in maxSpeed) {
    sortable.push([vehicle, maxSpeed[vehicle]]);
}

sortable.sort(function(a, b) {
    return a[1] - b[1];
});

//[["bike", 60], ["motorbike", 200], ["car", 300],
//["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

Example 6: sort function

var vehicules= [
   { nom: "Peugeot 208 1,2l PureTech", img:"208.png" , co2:108 },
   { nom: "Peugeot 5008 2.0 BlueHDi 150", img:"5008.png" , co2: 118 },
   { nom: "Golf GTI", img:"golfgti.png" , co2:148 },
   { nom: "Renault Clio 0.9 TCe 90", img:"clio.jpg" , co2:114 },
   { nom: "Audi A4 2.0 TDI 190", img:"a4.png" , co2: 111},
   { nom: "BMW Serie 2 Tourer 220d", img:"serie2tourer.png" , co2:124 },
   { nom: "Audi SQ7", img:"sq7.png" , co2:198 },
   { nom: "Audi TTS", img:"tts.png" , co2:159 },
];
vehicules.sort(function (a, b) {
   return a.co2 - b.co2;
});
vehicules.forEach(function(v) {
   console.log(v.nom+" avec "+v.co2+" g de CO2/km");    
});

Tags:

Php Example