arrayOperation.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * 判断两数组字符串是否相同(用于按钮权限验证),数组字符串中存在相同时会自动去重(按钮权限标识不会重复)
  3. * @param news 新数据
  4. * @param old 源数据
  5. * @returns 两数组相同返回 `true`,反之则反
  6. */
  7. export function judementSameArr(newArr: unknown[] | string[], oldArr: string[]): boolean {
  8. const news = removeDuplicate(newArr);
  9. const olds = removeDuplicate(oldArr);
  10. let count = 0;
  11. const leng = news.length;
  12. for (let i in olds) {
  13. for (let j in news) {
  14. if (olds[i] === news[j]) count++;
  15. }
  16. }
  17. return count === leng ? true : false;
  18. }
  19. /**
  20. * 判断两个对象是否相同
  21. * @param a 要比较的对象一
  22. * @param b 要比较的对象二
  23. * @returns 相同返回 true,反之则反
  24. */
  25. export function isObjectValueEqual<T>(a: T, b: T) {
  26. if (!a || !b) return false;
  27. let aProps = Object.getOwnPropertyNames(a);
  28. let bProps = Object.getOwnPropertyNames(b);
  29. if (aProps.length != bProps.length) return false;
  30. for (let i = 0; i < aProps.length; i++) {
  31. let propName = aProps[i];
  32. let propA = a[propName];
  33. let propB = b[propName];
  34. if (!b.hasOwnProperty(propName)) return false;
  35. if (propA instanceof Object) {
  36. if (!isObjectValueEqual(propA, propB)) return false;
  37. } else if (propA !== propB) {
  38. return false;
  39. }
  40. }
  41. return true;
  42. }
  43. /**
  44. * 数组、数组对象去重
  45. * @param arr 数组内容
  46. * @param attr 需要去重的键值(数组对象)
  47. * @returns
  48. */
  49. export function removeDuplicate(arr: any, attr?: string) {
  50. if (!arr && !arr.length) {
  51. return arr;
  52. } else {
  53. if (attr) {
  54. const obj: any = {};
  55. const newArr = arr.reduce((cur: any, item: any) => {
  56. obj[item[attr]] ? '' : (obj[item[attr]] = true && item[attr] && cur.push(item));
  57. return cur;
  58. }, []);
  59. return newArr;
  60. } else {
  61. return Array.from(new Set([...arr]));
  62. }
  63. }
  64. }