JavaScript 中文加数字组合排序算法:按文字一致性排序并按数字升序排列

要实现根据前面的文字一致性排序并按照后面的数字从小到大排序,可以按照以下步骤进行:

  1. 首先,将数组中的元素按照前面的文字进行分组,可以使用reduce()方法来实现。创建一个空对象,遍历数组中的元素,以元素的location属性作为键,将具有相同location值的元素添加到对应的键值数组中。

  2. 然后,对每个键值数组进行排序。使用sort()方法,比较函数需要按照后面的数字进行排序。可以使用正则表达式提取出数字部分,然后将字符串转换为数字进行比较。

  3. 最后,将所有分组后的数组合并为一个数组。可以使用flatMap()方法来将多个数组合并为一个数组。

下面是修改后的代码:

function sortChinese(arr) {
  const grouped = arr.reduce(function (acc, item) {
    const location = item.location;
    if (location != null) {
      if (!acc[location]) {
        acc[location] = [];
      }
      acc[location].push(item);
    } else {
      if (!acc['NoLocation']) {
        acc['NoLocation'] = [];
      }
      acc['NoLocation'].push(item);
    }
    return acc;
  }, {});

  for (let key in grouped) {
    grouped[key].sort(function (item1, item2) {
      const num1 = parseInt(item1.location.match(/\d+/)[0]);
      const num2 = parseInt(item2.location.match(/\d+/)[0]);
      return num1 - num2;
    });
  }

  const sortedArray = Object.values(grouped).flat();
  return sortedArray;
}

sortChinese(drugPackagingReview);

这样就可以根据前面的文字一致性排序,并按照后面的数字从小到大排序。

JavaScript 中文加数字组合排序算法:按文字一致性排序并按数字升序排列

原文地址: https://www.cveoy.top/t/topic/j1dE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录