[英]How to remove non-values from array
How to clean an array and keep only the numeric values of it. 如何清理数组并仅保留其数值。 This is my attempt. 这是我的尝试。
var array = ['5441ec', '37df21', '34d72', 'f3117'];
function normalize(input, scale, offset) {
input = input.map(Number); //remove non-numeric characters.
var cleanUp = input.filter(val => $.isNumeric(val) );
return cleanUp.map( values => values * scale + offset );
console.log(cleanUp);
};
normalize(array, 1, 0);
Simply with String.replace()
function: 只需使用String.replace()
函数即可:
var arr = ['5441ec', '37df21', '34d72', 'f3117'], res = arr.map((v) => Number(v.replace(/\\D+/g, ''))); console.log(res);
\\D+
- one or more non-digit character(s) \\D+
-一个或多个非数字字符 Slightly different to RomanPerekhrest's answer using match
rather than replace
. 与RomanPerekhrest的使用match
而不是replace
的答案略有不同。
var array = ['5441ec', '37df21', '34d72', 'f3117']; function normalize(arr) { return arr.map(el => Number(el.match(/\\d+/))); }; console.log(normalize(array));
Or, if you want to retain the elements as strings, just leave out the number coercion. 或者,如果您想将元素保留为字符串,则只需省略数字强制即可。
var array = ['5441ec', '37df21', '34d72', 'f3117']; function normalize(arr) { return arr.map(el => el.match(/\\d+/)[0]); }; console.log(normalize(array));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.