I want to remove special characters and letters from an array and calculate the sum of the remaining integers in the array, in JavaScript.
const arr = ["13,d42", "d44f2", "1g5", "1c42"];
let numbersOnly = (val) => {
if (typeof val === "number") {
// replace number with string to get only string values in an array.
return val;
} else {
let temp = val.split("");
// document.write(temp);
let newArr = [];
for (let i = 0; i < temp.length; i++) {
if (typeof temp[i].parseInt() === 'number') {
document.write(i)
newArr.push(temp[i]);
}
}
// return newArr;
// document.write(newArr)
}
};
let numbers = arr.map(numbersOnly).reduce((partialSum, a) => partialSum + a, 0);
document.write(numbers);
reduce over the array. For each string find the numbers using match with a simple regular expression, then join that array into one string, and then coerce it to a number.
const arr = ['13,d42', 'd44f2', '1g5', '1c42'];
const sum = arr.reduce((sum, str) => {
const num = Number(str.match(/\d/g).join(''));
return sum + num;
}, 0);
console.log(sum);
Sidenote: you probably shouldn't be using document.write:
⚠ Warning: Use of the
document.write()method is strongly discouraged.
1941 is correct answere. because "13,d42" is first element of the array. returns 1342
const arr = ["13,d42", "d44f2", "1g5", "1c42"];
console.log(arr.map(a => +a.match(/\d+/g).join('')).reduce((a, b) => a + b, 0)); // 1941 => the sum of [ 1342, 442, 15, 142 ]
Can this help you?
const arr = ["13,d42", "d44f2", "1g5", "1c42"];
const onlyNumbers = arr
.map((value) => value.replace(/[^0-9]/g, "")) // get just numbers
.reduce((pv, cv) => parseInt(pv) + parseInt(cv)); // add up the numbers
console.log(onlyNumbers);