Showing
1 changed file
with
60 additions
and
0 deletions
| ... | @@ -454,3 +454,63 @@ export function restTableHeight($refs) { | ... | @@ -454,3 +454,63 @@ export function restTableHeight($refs) { |
| 454 | let topHeaderClientHeight = document.querySelector(".headerRef").clientHeight; | 454 | let topHeaderClientHeight = document.querySelector(".headerRef").clientHeight; |
| 455 | return heigth + topHeaderClientHeight; | 455 | return heigth + topHeaderClientHeight; |
| 456 | } | 456 | } |
| 457 | + | ||
| 458 | +/** | ||
| 459 | + * Array Json去重 & 排序 | ||
| 460 | + * @param {Array} arr | ||
| 461 | + * @param {string || Object} keys | ||
| 462 | + * @description 对数组中指定的JSON字段去重和指定的字段进行排序 | ||
| 463 | + * @example | ||
| 464 | + * 当指定一个字段去重时:removeDuplicates(arr, "flightRoute") | ||
| 465 | + * 当指定一个字段去重并且排序如下: | ||
| 466 | + * const result = removeDuplicates(arr, { | ||
| 467 | + * duplicate: "flightRoute", // 去重字段 | ||
| 468 | + * sortType: "Number", // 排序类型:number、string | ||
| 469 | + * sortAttr: "routePriority", // 排序字段 | ||
| 470 | + * }) | ||
| 471 | + */ | ||
| 472 | +export function removeDuplicates(arr, keys) { | ||
| 473 | + const dict = {}; | ||
| 474 | + const result = { | ||
| 475 | + repeat: [], | ||
| 476 | + unique: [], | ||
| 477 | + }; | ||
| 478 | + let duplicate = keys; | ||
| 479 | + if (typeof keys == "object") { | ||
| 480 | + duplicate = keys.duplicate; | ||
| 481 | + } | ||
| 482 | + // 去重 | ||
| 483 | + result.unique = arr.reduce((res, currentValue) => { | ||
| 484 | + if (!dict[currentValue[duplicate]]) { | ||
| 485 | + dict[currentValue[duplicate]] = true; | ||
| 486 | + res.push(currentValue); | ||
| 487 | + } else { | ||
| 488 | + result.repeat.push(currentValue); | ||
| 489 | + } | ||
| 490 | + return res; | ||
| 491 | + }, []); | ||
| 492 | + // 返回去重结果 | ||
| 493 | + if (typeof keys == "string") return result; | ||
| 494 | + // 排序 | ||
| 495 | + if (typeof keys == "object") { | ||
| 496 | + if (keys.sortType.toLowerCase().trim() == "number") { | ||
| 497 | + if (result.repeat.length) { | ||
| 498 | + result.repeat = sortFn("repeat"); | ||
| 499 | + } | ||
| 500 | + if (result.unique.length) { | ||
| 501 | + result.unique = sortFn("unique"); | ||
| 502 | + } | ||
| 503 | + return result; | ||
| 504 | + } | ||
| 505 | + } | ||
| 506 | + // 排序方法 | ||
| 507 | + function sortFn(attr) { | ||
| 508 | + if (isNaN(Number(result[attr][0][keys.sortAttr]))) { | ||
| 509 | + return result[attr].sort((a, b) => | ||
| 510 | + a[keys.sortAttr].localeCompare(b[keys.sortAttr]) | ||
| 511 | + ); // 按字母排序 | ||
| 512 | + } else { | ||
| 513 | + return result[attr].sort((a, b) => a[keys.sortAttr] - b[keys.sortAttr]); // 按数字排序 | ||
| 514 | + } | ||
| 515 | + } | ||
| 516 | +} | ... | ... |
-
Please register or login to post a comment