【问题标题】:Extract Numbers from Array mixed with strings - Javascript从与字符串混合的数组中提取数字 - Javascript
【发布时间】:2018-09-05 16:18:29
【问题描述】:

我有一个由字符串和数字组成的数组。我需要对数字进行排序或更好地仅提取另一个数组中的数字。示例如下:

 const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.']

我需要变成这样

 const filtered = [23456, 34, 23455]

我用 split(' ') 方法用逗号分隔它们,但不知道如何为 JS 过滤它们它们都是字符串。

【问题讨论】:

  • 您是否需要两个结果数组,一个带有字符串,另一个带有数字?就是它?到目前为止,您尝试过什么代码?
  • 如果您选择自行进一步研究,您使用“过滤器”这个词这一事实应该为您指明正确的方向

标签: javascript arrays numbers mixed


【解决方案1】:

这可能是一个可能的解决方案,

请参阅 MDN 了解 map()replace()trim()split()

const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.'];
filtered = myArr[0].replace(/\D+/g, ' ').trim().split(' ').map(e => parseInt(e));
console.log(filtered);

const regex = /\d+/gm;
const str = `Prihodi 23456 danaci 34 razhodi 23455 I drugi`;
let m;
const filter = [];
while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }

  // The result can be accessed through the `m`-variable.
  m.forEach((match, groupIndex) => {
    filter.push(parseInt(match))
  });
}

console.log(filter);

【讨论】:

    【解决方案2】:

    const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.'];
    var result=[];
    myArr.forEach(function(v){
      arr=v.match(/[-+]?[0-9]*\.?[0-9]+/g);
      result=result.concat(arr);
    });
    const filtered = result.map(function (x) { 
     return parseInt(x, 10); 
       });
    console.log(filtered)

    【讨论】:

    • 这会返回一个数字的字符串表示数组,而不是 OP 要求的。
    • 改成数字
    【解决方案3】:

    const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.']
    const reduced = myArr[0].split(' ').reduce((arr, item) => {
      const parsed = Number.parseInt(item)
      if(!Number.isNaN(parsed)) arr.push(parsed)
      return arr
    }, [])
    console.log(reduced)

    【讨论】:

      【解决方案4】:

      你可以用简单的RegexArray.prototype.map来做到这一点:

      const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.']
      
      const result = myArr[0].match(/\d+/gi).map(Number);
      
      console.log(result);

      【讨论】:

        【解决方案5】:

        我很久以前就完成了任务。但是现在我找到了这个快速的解决方案

        const arr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.']
        
        const res = arr.join('')
        .split(' ')
        .filter(e => +e)
        .map(num => +num);
        
        console.log(res);
        

        【讨论】:

          【解决方案6】:

          const array = ["string1", -35, "string2", 888, "blablabla", 987, NaN];

          const mapArray = array.filter((item) => {
            if (item < 0 || item >= 0) return item;
          });
          
          console.log(mapArray);
          

          【讨论】:

          • 请注意,如果原始数组包含负数,这将不起作用。
          猜你喜欢
          • 2021-12-19
          • 2021-03-15
          • 2017-07-20
          • 2012-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多