Skip to content

Instantly share code, notes, and snippets.

@hungdev
Created November 26, 2020 16:50
Show Gist options
  • Select an option

  • Save hungdev/6753a83202c377212e3cf40fcb107294 to your computer and use it in GitHub Desktop.

Select an option

Save hungdev/6753a83202c377212e3cf40fcb107294 to your computer and use it in GitHub Desktop.
sort text and number
export const sortTable = (data, sortKey, direction) => {
  const reverse = direction === "ascending" ? 1 : -1;
  const so = data.sort((nameA, nameB) => {
    const isString = Number.isNaN(Number(nameA)) // true => string
    if (isString) {
      if (nameA?.[sortKey]?.toUpperCase() < nameB?.[sortKey]?.toUpperCase()) {
        return -1 * reverse;
      }
      if (nameA?.[sortKey]?.toUpperCase() > nameB?.[sortKey]?.toUpperCase()) {
        return 1 * reverse;
      }
      // names must be equal
      return 0;
    } else {
      return direction === "ascending" ? nameA?.[sortKey] - nameB?.[sortKey] : nameB?.[sortKey] - nameA?.[sortKey]
    }
  })
  return so
}
@hungdev
Copy link
Author

hungdev commented Nov 27, 2020

@shunz19
It serves my application, because my data is Array object. So simple version is:

const alpString = ['A', 'D', 'C', 'B'];
const months = ['1', '5', '20', '15'];
var numericStringArray = ['80', '9', '700'];

function sortTable(data) {
  return data.sort((nameA,nameB) =>{
    const isString = Number.isNaN(Number(nameA)) // true => string
    if(isString) {
      if (nameA.toUpperCase() < nameB.toUpperCase()) {
        return -1;
      }
      if (nameA.toUpperCase() > nameB.toUpperCase()) {
        return 1;
      }
      // names must be equal
      return 0;
    } else {
      return nameA - nameB
    }
  })
}

console.log(sortTable(alpString))
console.log(sortTable(months))

https://repl.it/@hungdev/InsubstantialFastScientist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment