javascript - 逻辑错误! in 使用字符串在指定位置插入数组

标签 javascript node.js arrays sorting

我正在编写一个函数来提取单词中包含的单词的索引, 例如:4of Fo1r pe6ople g3ood th5e the2 这应该按顺序对齐, 下面是代码,

function order(words){
    var result = []
    var sorting = words.split(' ').sort() 
    console.log(sorting);
    for(let i=0; i<sorting.length;i++)
    {
      var temp = sorting[i].split('').sort()//By this the words in the sentence get sorted and i will get the index(number) of the corresponding word at first position.
      console.log(temp);
      var valueHolder = parseInt(temp) //I will take the above obtained value and convert it into integer
        console.log(valueHolder);
      result.splice((valueHolder-1),0,sorting[i]) //will pass the index here
    }
    console.log(result);
  }

但我得到了错误的输出:[ 'Fo1r', 'the2', '4of', 'g3ood', 'pe6ople', 'th5e' ] 我错过了什么吗,谁能帮我解决这个问题谢谢。 以上 array.splice(index,0,item) 只会在指定位置插入元素,并且 0

预期输出为:[ 'Fo1r', 'the2', 'g3ood', '4of', 'th5e','pe6ople' ]

最佳答案

您可以使用正则表达式然后解析 9 以上的数字。

正则表达式 const r =/\d+/; 查找一位或多位数字。然后在排序方法 a.match(r) 中使用正则表达式,然后解析和比较结果数字。

const str = '4of Fo1r pe6ople g3ood th5e no71w the2';

function order(words) {
  let result = [];
  let sorting = words.split(' ');
  const r = /\d+/;
  
  sorting.sort((a,b) => {
    return parseInt(a.match(r)) - parseInt(b.match(r));
  });
  console.log(sorting.join(' '));
}
order(str);

关于javascript - 逻辑错误! in 使用字符串在指定位置插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67329283/

相关文章:

javascript - 一旦应用程序在asp.net中正确运行,就可以防止返回

javascript - 获取数组对象中第一个对象的键

node.js - Node 使用 ssh 从远程计算机读取文件流

Node.js Azure Web 应用程序 Windows 500.1001 错误

node.js - 填充队列时 Azure Functions 中的超时

javascript - 使用 javascript/typescript 创建一个对象数组,使其具有 3 个数组的所有可能性组合

java - 一次从数组中拉出 10 个项目的最佳方法

javascript - Angular Modal,我需要指定关闭行为吗

javascript - 为什么元素没有以 Angular 动态添加

javascript - ExtJs Store.Load() 与 Model.Load()