简体   繁体   English

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

[英]Extract Numbers from Array mixed with strings - Javascript

I have an array from strings and numbers.我有一个来自字符串和数字的数组。 I need to sort the numbers or better to extract only the numbers in another array.我需要对数字进行排序,或者更好地仅提取另一个数组中的数字。 Here is the example:这是示例:

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

I need to make it like this我需要让它像这样

 const filtered = [23456, 34, 23455]

I used split(' ') method to separate them with comma but don't know how to filter them for JS they all are strings.我使用 split(' ') 方法用逗号分隔它们,但不知道如何为 JS 过滤它们,它们都是字符串。

This could be a possible solution,这可能是一个可能的解决方案,

See MDN for map() , replace() , trim() and split()有关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);

 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)

 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)

You can do it with simple Regex and Array.prototype.map :你可以用简单的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);

I finish the task long time ago.我很久以前就完成了任务。 However now I found this quick solution但是现在我找到了这个快速解决方案

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

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

console.log(res);

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

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

console.log(mapArray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM