对一串数字进行排序,每个数字里面都有一个字母.确保在原始数组中保持相同的重复项位置

sorting a string of numbers that each have a letter inside. making sure to keep the same position of duplicates as in the original array

本文关键字:数字 数组 原始 确保 位置 有一个 一串 排序      更新时间:2023-09-26

我有一串数字。每个数字里面随机放一个字母。我需要根据每个数字里面的字母按字母顺序对这些数字进行排序。但是,如果有重复,我必须保持原始字符串的顺序。例如:"c21 32b 43a 2c3"必须排序为"43a 32b c21 2c3",然后我需要去掉字母。

到目前为止是这样的:

function cats(s) {
  let arr = s.split(' ').sort(function (a,b) {
      return a.match(/[a-z]/i)[0].localeCompare(b.match(/[a-z]/i)[0]);
  });
console.log(arr)
   for (i = 0; i < arr.length; i++) {
    arr[i] = arr[i].replace(/'D/g,'');
  }
  console.log(arr)
}
cats('y381 6a684 9c94 5x346 c9541 31w1 440x16 x620 1b33 y4773 c3019');

我似乎不能把这些重复的字母正确地排序。这很重要,因为稍后我需要对这些数字进行数学运算,而顺序对于得到正确的解很重要。

您可以保留一个分割字符串的数组作为引用,并使用索引来排序,当字母匹配

let refArr = s.split(' ');
let arr = refArr.slice().sort(function (a,b) {
  let aLetter = a.match(/[a-z]/i)[0], bLetter=b.match(/[a-z]/i)[0];
  if(aLetter === bLetter){
     return refArr.indexOf(a) - refArr.indexOf(b);
  }else{
     return aLetter.localeCompare(bLetter);
  }     
});

你只需要一个小mod,基本上在排序之前做一个map,存储数组索引,排序然后可以使用索引做一个复合排序,然后我们使用map放回你之前的格式。

function cats(s) {
  let arr = s.split(' ').
     map(function (v,i) { return {v:v, i:i }}).
     sort(function (a,b) {
       return a.v.match(/[a-z]/i)[0].localeCompare(b.v.match(/[a-z]/i)[0]) || a.i - b.i}).
     map(function (v) { return v.v; });        
  console.log(arr)
  for (i = 0; i < arr.length; i++) {
    arr[i] = arr[i].replace(/'D/g,'');
  }
  console.log(arr)
}
cats('y381 6a684 9c94 5x346 c9541 31w1 440x16 x620 1b33 y4773 c3019');

您可以使用map排序并获得包含已排序项的新数组。这保持了相同字母项的顺序。

var array = 'y381 6a684 9c94 5x346 c9541 31w1 440x16 x620 1b33 y4773 c3019'.split(' ');
var mapped = array.map((el, i) => ({ index: i, letter: el.match(/[a-z]/i)[0] }));
// sorting the mapped array containing the reduced values
mapped.sort((a, b) => a.letter.localeCompare(b.letter) || a.index - b.index);
// container for the resulting order
var result = mapped.map(el => array[el.index]);
   
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }