Reputation: 29
The for loop just return me 0 as cantidad value, I supposed it should have returned 2 due facturas has 2x pagado. Ty
facturas=["Mario:pagado","Vane:pagado","Velez:deuda"];
function extractNames(string){
end=string.indexOf(":");
return string.slice(0,end);
}
function countPaids(texto){
count=0;
start=texto.indexOf(":")+1;
if(texto.slice(start,texto.length)=="pagado"){
count++;}
return {cantidad:count};
}
for(i=0;i<facturas.length;i++){
factura=facturas[i];
for(factura=0;factura<facturas.length;factura++){
countPaids(facturas[factura]);
}
}
Upvotes: -1
Views: 76
Reputation: 94101
Given that the other answer already solves your particular issue, I would provide some input on how to improve your code:
You forgot to declare all your variables. When you omit the var
keyword, your variables become implicit globals; you don't want this.
I would suggest rethinking your data structure. In JavaScript we have arrays and objects. A common way to store information is in collections, which are simply arrays of objects. This will improve readability of your code, and you can easily loop collections with native JavaScript methods and your own helpers. For example:
// A collection
var facturas = [
{name: 'Mario', state: 'pagado'},
{name: 'Vane', state: 'pagado'},
{name: 'Velez', state: 'deuda'}
];
// Helpers to work with collections
var dot = function(s) {
return function(x) {
return x[s];
};
};
var eq = function(s) {
return function(x) {
return x == s;
};
};
// Example
var states = facturas.map(dot('state')); //=> ['pagado','pagado','deuda']
var totalPaid = states.filter(eq('pagado')).length; //=> 2
Upvotes: 2
Reputation: 141829
You are calling a function which resets count to 0
every time. Do your counting in your loop instead:
var facturas = ["Mario:pagado","Vane:pagado","Velez:deuda"];
function extractNames(string){
var end = string.indexOf(":");
return string.slice(0, end);
}
/* returns true if the string contains "pagado" after the ":" */
function isPaid(texto){
var start = texto.indexOf(":") + 1;
return texto.slice(start,texto.length) == "pagado";
}
var count = 0;
for(var factura = 0; factura < facturas.length; factura++){
count += isPaid(facturas[factura]);
}
// count == 2 here.
Don't forget to declare all your variables within the function scope you want to use them by using the var
keyword.
Upvotes: 0