“JavaScript -Sortierung” Code-Antworten

JS -Array -Sortierung

numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
Worried Wildebeest

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;
});
Clever Crocodile

JavaScript -Sortierung

var names = ["Peter", "Emma", "Jack", "Mia", "Eric"];
names.sort(); // ["Emma", "Eric", "Jack", "Mia", "Peter"]

var objs = [
  {name: "Peter", age: 35},
  {name: "Emma", age: 21},
  {name: "Jack", age: 53}
];

objs.sort(function(a, b) {
  return a.age - b.age;
}); // Sort by age (lowest first)
TC5550

JavaScript -Sortierung

homes.sort(function(a, b) {
    return parseFloat(a.price) - parseFloat(b.price);
});
Fancy Fox

JavaScript -Sortierung

homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
Fancy Fox

JavaScript -Sortierung

let arr = [1,2,3,3,4]

arr.sort() => sorts in ascending order from right to left


// You can sort in custom orders by defining a custom comparison function
// ex:

arr.sort(function compareNumbers(firstNumber, secondNumber){
	/*
    if a negative number is returned, firstNumber will be the first number in the output
    if a positive number is returned, secondNumber will be the first number in the output
    if a 0 is returned, it will default to returning them in the position they're already in
    */
  
	// ascending order
  	// return firstNumber - secondNumber
  
    // descending order
    //return secondNumber - firstNumber
  
  	// Always want 3's to come first:
  	/*
  	if firstNumber === 3{
    	return -1
    }
  	if secondNumber === 3{
    	return 1
    }
  	return secondNumber - firstNumber
  	*/
  
  
})



QuietHumility

Ähnliche Antworten wie “JavaScript -Sortierung”

Fragen ähnlich wie “JavaScript -Sortierung”

Weitere verwandte Antworten zu “JavaScript -Sortierung” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen