0
Q:

sort array 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(function(a, b){return a-b});

 
8
var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)
7
var ages = [18, 21, 9, 41, 35, 24]
ages.sort(function(a, b) {
  return a - b
})
// => [9, 18, 21, 24, 35, 41]
2
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
arr = ['width', 'score', done', 'neither' ]
arr.sort() // results to ["done", "neither", "score", "width"]

arr.sort((a,b) => a.localeCompare(b)) 
// if a-b (based on their unicode values) produces a negative value, 
// a comes before b, the reverse if positive, and as is if zero

//When you sort an array with .sort(), it assumes that you are sorting strings
//. When sorting numbers, the default behavior will not sort them properly.
arr = [21, 7, 5.6, 102, 79]
arr.sort((a, b) => a - b) // results to [5.6, 7, 21, 79, 102]
// b - a will give you the reverse order of the sorted items 

//this explnation in not mine
1

New to Communities?

Join the community