I'm trying to get the average of an array containing strings, numbers and string numbers. The average must take into account the stringified numbers.
I've used reduce and can get the average so far, but cannot get it to work ignoring the words. This is what I have at the moment.
<script>
function average() {
const array = [4, 45, 'hgd', '50', 87, 8, 'dhgs', 85, 4, '9'];
let sum = arr.reduce((x, y) =>
typeof +x === 'Number' ? x + y : +x + y);
sum = sum / arr.length;
return document.write(sum);
}
</script>
Anyone could give me a hand? Thank you.
Try this:
a.reduce((x, y) => +y ? x + +y : x)
for the average, you need to get the total array size, which you can do it in that reduce
function:
let count = 0;
a.reduce((x, y) => {
if (+y) {
count ++;
x += +y;
}
return x;
}, 0);
The second input of reduce
is, as the developer on mozilla says, the initial value, which in this case we need to be 0, so all the array members get into y
(if not provided, the first element would be ignored) and the count
gives true result
UPDATE 1 If you want only the string numbers , you must use this:
let sum = a.reduce((x, y) => typeof y !== 'number' && +y ? x + +y : x, 0)
and for the average, you need this :
let count = 0;
let sum = a.reduce((x, y) => {
if (typeof y !== 'number' && +y) {
x + +y;
count ++;
}
return x;
}, 0);
let average = sum / count;
This works exactly as you expected.
You could filter and map the numbers to number, while respecting zero values as well and then add all values and divide by the length of the number count.
const not = f => (...a) => !f(...a), add = (a, b) => a + b, array = [4, 45, 'hgd', '50', 87, 8, 'dhgs', 85, 4, '9', '1a'], temp = array.filter(not(isNaN)).map(Number), avg = temp.reduce(add) / temp.length; console.log(avg);
Assuming you only want average of actual numeric values filter out the non numeric strings and reduce the others
const arr = [4, 45, 'hgd', '50', 87, 8, 'dhgs', 85, 4, '9']; const nums = arr.filter(n => !isNaN(n)).map(Number) const ave = nums.reduce((x, y) => x + y) / (nums.length || 1); console.log(ave)
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.