从与字符串混合的数组中提取数字-Javascript

时间:2018-09-05 16:18:30

标签: javascript arrays numbers mixed

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

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

我需要像这样

 const filtered = [23456, 34, 23455]

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

6 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

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)

答案 2 :(得分:0)

这可能是一种解决方案,

请参见map()replace()trim()split()的MDN

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);

OR

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);

答案 3 :(得分:0)

您可以使用简单的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);

答案 4 :(得分:0)

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

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

const res = arr.join('')
.split(' ')
.filter(e => +e)
.map(num => +num);

console.log(res);

答案 5 :(得分:0)

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

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

console.log(mapArray);