javascript sort array of objects ascending and descending order

61

Sorting an array of objects on both ascending and descending order on same click -

self.isAscending = true;

self.sortTitle = function () {
 if(self.isAscending){ 
   self.arr= self.arr.sort((a, b) => (a.title > b.title) ? 1 : -1);
 }else{
   self.arr= self.arr.sort((a, b) => (a.title > b.title) ? -1 : 1);
 }
 self.isAscending = !self.isAscending;
}

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

sort array of objects in ascending order in js -

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

javascript sort array of objects by key value ascending and descending order -

 function compareValues(key, order = 'asc') {
  return function innerSort(a, b) {
    if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
      // property doesn't exist on either object
      return 0;
    }

    const varA = (typeof a[key] === 'string')
      ? a[key].toUpperCase() : a[key];
    const varB = (typeof b[key] === 'string')
      ? b[key].toUpperCase() : b[key];

    let comparison = 0;
    if (varA > varB) {
      comparison = 1;
    } else if (varA < varB) {
      comparison = -1;
    }
    return (
      (order === 'desc') ? (comparison * -1) : comparison
    );
  };
}

Comments

Submit
0 Comments