Reputation: 53
I want to get the average from input type="text". In the input type text, it has the format 1,2,3. When they click on the button it should alert them the average. Here is my code:
In the input type text in the snippet type in 1,2,3. Then you will see the problem.
function averagevalue(){
var numberstouse = document.getElementById('average').value;
const average = array => array.reduce((a, b) => a + b) / array.length;
alert(average([numberstouse]));
}
<input type="text" id="average" value>
<button type="btn" onclick="averagevalue()">Avg</button>
But the problem is, as you can see in the snippet, it says the value NaN. But in the alert, I want to says the average. Any help is appreciated.
Upvotes: 1
Views: 86
Reputation: 24
The value is a comma seperated string. so we use the .split()
method on it with, ,
as an argument to that method and that will return a list without the comma.
Edit : I forgot to convert the items in list to number. fixed !
function averagevalue(){
var numberstouse = document.getElementById('average').value;
numberstouse = numberstouse.split(',')
numberstouse = numberstouse.map(str => Number(str));
const average = array => array.reduce((a, b) => a + b) / array.length
alert(average(numberstouse));
}
<input type="text" id="average" value=>
<button type="btn" onclick="averagevalue()">Avg</button>
Upvotes: 1
Reputation: 548
you need to pass the whole input and split it to make a new array, and its elements to floats you could use this instead :
function averagevalue(){
var numberstouse = document.getElementById('average').value;
const average = numberstouse =>
{
let newArr = numberstouse.split(",");
let val = newArr.reduce((a,b)=>parseFloat(a)+parseFloat(b)) / newArr.length;
return val;
}
alert(average(numberstouse));
}
Upvotes: 0
Reputation: 3537
Use Split to convert the input to an array
The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
function averagevalue(){
var numberstouse = document.getElementById('average').value;
const average = array => array.reduce((a, b) => Number(a) + Number(b)) / array.length;
alert(average(numberstouse.split(',')));
}
<input type="text" id="average" value=>
<button type="btn" onclick="averagevalue()">Avg</button>
Upvotes: 1