Q:

sort method 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)
11
var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)
7
var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)

4
const sort = arr => arr.sort((a, b) => a - b);
//By default,the sort() function sorts values as strings.Fix this by providing a compare function.
// Example
sort([1, 5, 2, 4, 3]);      // [1, 2, 3, 4, 5]
4
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

// [1, 2, 3, 4, 5]
3
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
5
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
1
homes.sort(function(a, b) {
    return parseFloat(a.price) - parseFloat(b.price);
});
3

New to Communities?

Join the community