node sort array code example

Example 1: sort javascript array

var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)

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: sort function in react js

this.state.data.sort((a, b) => a.timeM > b.timeM ? 1:-1).map(
    (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)

Example 4: array sort js

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

Example 5: javascript sort

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

Example 6: javascript sort array in ascending order

//sorts arrays of numbers
function myFunction() {
  points.sort(function(a, b){return a-b});
  document.getElementById("demo").innerHTML = points;
}

Tags:

Php Example