Table Sort

by jacobwsmith

JavaScript

/* 
A reuseable sort method called tableSort(data, attr, order) where data is and array of objects, attr is the attribute to sort and order is either 'dsc' or 'asc'. Note: data attributes can be either "strings", "numbers", or "strings as numbers" (these need to be sorted as numbers).

Example:

*/
console.clear();

const data = [
	{id: 4, name: 'd', total: 'N/A'},
  {id: 2, name: 'B', total: '--'},
  {id: 3, name: 'a', total: '0.0'},
  {id: 5, name: 'E', total: '88.1'},
  {id: 1, name: 'C', total: '9.0'},
];

function tableSort(data, attr, order){
  return data.sort((a, b) => {
    // In Unicode, numbers come before upper case letters,
    // which come before lower case letters.
    // we need to adjust for that
    const aVal = convertStringToNumber(a[attr]);
    const bVal = convertStringToNumber(b[attr]);

    if(typeof aVal === 'number' && typeof bVal === 'number'){
      return numberSort(aVal, bVal, order);
    } 
    if(typeof aVal === 'string' && typeof bVal === 'string') {
      return stringSort(aVal, bVal, order);
    } 
    return customSort(aVal, bVal, order);
  	
  });
  
  function convertStringToNumber(str){
  	const num = +str;
    if (num || num === 0) {
      return num;
    }
    return str; // can't convert keep as string
  }
  function numberSort(a, b, order){
    if(order === 'dsc'){
    	return b - a;
    }
    return a- b;
  }
  function stringSort(a, b, order){
  	var nameA = a.toUpperCase(); // ignore upper and lowercase
    var nameB = b.toUpperCase(); // ignore upper and lowercase
    if (nameA < nameB) {
      return order === 'dsc' ? 1 : -1;
    }
    if (nameA > nameB) {
      return order === 'dsc' ? -1 : 1;
    }
    // names must be equal
    return 0;
  }
  function customSort(a, b, order){
  	if(typeof a === 'string' && typeof b === 'number'){
    	return order === 'dsc' ? 1 : -1;
    }
    if(typeof a === 'number' && typeof b === 'string'){
    	return order === 'dsc' ? -1 : 1;
    }
  }
}

/// TESTS ///
// Test Numbers...