“clasificación de JavaScript” Código de respuesta

Clasificación de matriz JS

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

clasificación de JavaScript

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

clasificación de JavaScript

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

clasificación de JavaScript

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

clasificación de JavaScript

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

Respuestas similares a “clasificación de JavaScript”

Preguntas similares a “clasificación de JavaScript”

Más respuestas relacionadas con “clasificación de JavaScript” en JavaScript

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código