Reputation:
(1)
I have here an array that is a mix of strings and ints:
var newArr = [ 22, 7, "2761", 16, "91981", "37728", "13909", "247214", "8804", 6, 2 ]
My ultimate goal is to remove the values that are ints, and add the other values.
One way I tried to achieve this was to first convert all to ints:
for (element in newArr) {
newArr[element] = parseInt(newArr[element], 10);
}
Is this the best way to do that? It seems to output an array of ints like this:
var newArr = [ 22, 7, 2761, 16, 91981, 37728, 13909, 247214, 8804, 6, 2 ];
(2)
Then I would like to only sum elements in newArr that are above the value of 30. This is my code:
var newArr = [ 22, 7, 2761, 16, 91981, 37728, 13909, 247214, 8804, 6, 2 ];
for (element in newArr) {
if (newArr[element] > 30) {
sum += newArr[element];
}
}
It doesn't seem to be working. Please help.
(3) A final question is:
How could I just eliminate the ints from newArr in step (1), as this would negate the need for the other code, I guess.
A simple solution using only javascript syntax (no jquery) would be appreciated. (unless the overwhelming consensus is that jquery would be a better option) Thanks Javascript Ninjas!
Upvotes: 0
Views: 823
Reputation: 318
I think the best approach to do all this in single iteration would be .
Using Array's Reduce Right : Sample Use:
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) { return previousValue + currentValue; });
You can check the previousValue and currentValue with typeof and return the addition if parseInt() return's 30 or more.
Upvotes: 0
Reputation: 34217
Detect the type then remove them: Here I go through the array, then remove the numbers then go through it again:
var newArr = [22, 7, "2761", 16, "91981", "37728", "13909", "247214", "8804", 6, 2];
for (element in newArr) {
alert(typeof newArr[element] + ":" + newArr[element]);
}
for (var i = newArr.length; i--;) {
if (typeof newArr[i] === "number") {
newArr.splice(i, 1);
}
}
alert(newArr.length);
for (element in newArr) {
alert(typeof newArr[element] + ":" + newArr[element]);
}
Upvotes: 0
Reputation: 32511
First, you might want to look into Array.map. This will allow you to convert them all to ints.
var result = newArr.map(function(x) {
return parseInt(x, 10);
});
Then you can use Array.filter to remove any elements less than or equal to 30.
result = result.filter(function(x) {
return x > 30;
});
Finally, you can use Array.reduce to sum them all together.
sum = result.reduce(function(sum, x) {
return sum + x;
}, 0);
There are numerous ways of accomplishing this but I like this approach because you can chain it together.
var sum = newArray.map(function(x) {
return parseInt(x, 10);
})
.filter(function(x) {
return x > 30;
})
.reduce(function(sum, x) {
return sum + x;
}, 0);
Upvotes: 5