使用 A-Z 集自定义排序 Javascript

问题描述 投票:0回答:1

我有一个数组

[
  'A. Wound Location and Measurements',
  'B. Wound Bed',
  'C. Surrounding Tissue',
  'D. Drainage',
  'Haroon Question Group Without Show PCP',
  'Haroon Question Group With Show PCP',
  'A. Wound Location and Measurements',
  'B. Wound Bed',
  'C. Surrounding Tissue',
  'D. Drainage',
];

我想以这样的方式对其进行排序,使其应该像这样返回

[
  'A. Wound Location and Measurements',
  'B. Wound Bed',
  'C. Surrounding Tissue',
  'D. Drainage',
  'A. Wound Location and Measurements',
  'B. Wound Bed',
  'C. Surrounding Tissue',
  'D. Drainage',
  'Haroon Question Group With Show PCP',
  'Haroon Question Group Without Show PCP'
]

它应该完成整个 A-Z 组,然后从 A-Z 重新开始

javascript sorting
1个回答
0
投票

您能提供更多信息吗?我创建了一个例子,请测试一下是否如你所愿。

function sortArray(arr) {
  // Function to check if an item belongs to the A-D set
  const isADSet = item => /^(A|B|C|D)\./.test(item);

  // Split the array into AD set items and others
  const adSetItems = arr.filter(isADSet);
  const otherItems = arr.filter(item => !isADSet(item));

  // Since AD set items should maintain their order and appear twice,
  // and considering they are already in order within each set,
  // we concatenate them directly. For otherItems, we sort them as per the requirement.
  otherItems.sort((a, b) => {
    if (a.includes('With Show PCP') && b.includes('Without Show PCP')) return -1;
    if (a.includes('Without Show PCP') && b.includes('With Show PCP')) return 1;
    return 0;
  });

  // Concatenate the sorted parts in the required order
  return [...adSetItems, ...adSetItems, ...otherItems];
}

// Original array
const items = [
  'A. Wound Location and Measurements',
  'B. Wound Bed',
  'C. Surrounding Tissue',
  'D. Drainage',
  'Haroon Question Group Without Show PCP',
  'Haroon Question Group With Show PCP',
  'A. Wound Location and Measurements',
  'B. Wound Bed',
  'C. Surrounding Tissue',
  'D. Drainage',
];

// Sorted array
console.log(sortArray(items));
© www.soinside.com 2019 - 2024. All rights reserved.