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:
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) Slightly different to RomanPerekhrest's answer using match
rather than 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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.