arrayUtils.ts 940 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import type { AnyJson } from '~/types/data'
  2. export default class ArrayUtils {
  3. /**
  4. * Trie un tableau
  5. *
  6. * @param array
  7. * @param reverse
  8. */
  9. public static 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. public static 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. }