Reputation: 11
I have array like this in JavaScript
var a = [1,2,3,4,5,"4","12","2",6,7,"4",3,"2"];
My questions are
How do I split the array to change, (comma) to ";"
How do I return the number of strings in the array as well as return total value regardless of variable type.
How do I return the average value (regardless of variable type again)
Upvotes: 0
Views: 201
Reputation: 386746
All results in one loop.
0 ... n-4: Data
n-3: Count of all strings
n-2: Sum
n-1: Average
var data = [1, 2, 3, 4, 5, "4", "12", "2", 6, 7, "4", 3, "2"],
result = data.concat(data.reduce(function (r, a, i) {
typeof a === 'string' && r[0]++;
r[1] += +a;
r[2] = r[1] / i;
return r;
}, [0, 0, 0])).join(';');
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Upvotes: 0
Reputation: 476
Change array separator:
a.join(';');
as referenced here
Number of strings in array:
var stringCount = 0;
for (var i = 0; i < a.length; i++){
if (typeof a[i] === 'string'){
stringCount++;
}
}
alert("The number of strings is: " + stringCount);
Test it here: https://jsfiddle.net/6c42nugy/2/
Number of all elements in array:
var entireLength = a.length;
Percentage per type in comparison to whole
var stringPerc = (stringCount)/(stringCount + entireLength)
var otherPerc = (entireLength - stringCount)/(stringCount + entireLength)
Upvotes: 1
Reputation: 3597
Here is my version:
var a = [1,2,3,4,5,"4","12","2",6,7,"4",3,"2"], sum = 0, strings = 0;
var joined = a.join(';');
console.log("Joined: " + joined);
for (var i = 0; i < a.length; i++) {
sum += parseInt(a[i]);
if (typeof a[i] === "string") {
strings++;
}
}
var avg = sum / a.length;
console.log('Sum: ' + sum);
console.log('Average: ' + avg);
console.log('Strings: ' + strings);
And link to JSFiddle.
Upvotes: 0
Reputation: 758
Use a.join(';');
to convert the array into a string separated by semicolons.
To return the number of strings in the array, simply iterate through it and use toString.call()
like this:
var total = 0;
for (var i = 0, n = a.length; i < n; i++) {
if (toString.call(a[i]) === '[object String]') total++;
}
To simply return the total number of items, you can do a.length
.
If you want the total value as in all the elements summed, you can do this:
var total = 0;
for (var i = 0, n = a.length; i < n; i++) {
total += parseInt(a[i]);
}
If you want the average, just take the code above and do total / a.length;
.
Upvotes: 0
Reputation: 2156
Answering Question 1
1.Convert it to a string
var x=a.toString();
2.Perform a global replace
var y= x.replace(/,/g,";");
3.This gives you "1;2;3;4;5;4;12;2;6;7;4;3;2"
For Question 2
Simply use the a.length
method.This will give you the total number of elements.I'm not sure about the String elements part.
Upvotes: 1