arrayUtils.ts 928 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import type { AnyJson } from '~/types/data'
  2. const ArrayUtils = {
  3. /**
  4. * Trie un tableau
  5. *
  6. * @param array
  7. * @param reverse
  8. */
  9. sort(
  10. array: Array<object | string | number>,
  11. reverse: boolean = false,
  12. ): Array<object | string | number> {
  13. return array.sort((a, b) => {
  14. return (a < b ? -1 : a > b ? 1 : 0) * (reverse ? -1 : 1)
  15. })
  16. },
  17. /**
  18. * Trie un tableau d'objets selon une propriété commune
  19. *
  20. * @param array Une array d'objets
  21. * @param property Le nom d'une propriété possédée par tous les objets
  22. * @param reverse
  23. */
  24. sortObjectsByProp(
  25. array: Array<AnyJson>,
  26. property: string,
  27. reverse: boolean = false,
  28. ): Array<AnyJson> {
  29. return array.sort((a: AnyJson, b: AnyJson) => {
  30. return (
  31. (a[property] < b[property] ? -1 : a[property] > b[property] ? 1 : 0) *
  32. (reverse ? -1 : 1)
  33. )
  34. })
  35. },
  36. }
  37. export default ArrayUtils