Reputation: 93
The values of "end" after the loop are lost and I do not understand the reason.
var horas = ['2','6']
var x6 = ['1','2','3','4','5','6','7']
var x5 = ['uno','dos','tres','cuatro','cinco','seis','siete']
var final = [];
for (var i = 0; i <= x6.length; i++)
{
if(x6[i].indexOf(horas[0])!==-1) {final.push(x5[i]);}
if(x6[i].indexOf(horas[1])!==-1) {final.push(x5[i]);}
if(x6[i].indexOf(horas[2])!==-1) {final.push(x5[i]);}
console.log(final); // here yes exists
}
console.log(final); // does not exists, Does not show anything
Upvotes: 1
Views: 147
Reputation: 386670
You need to keep the index inside of the array.
for (var i = 0; i < x6.length; i++) {
// ^
var horas = ['2', '6']
var x6 = ['1', '2', '3', '4', '5', '6', '7']
var x5 = ['uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete']
var final = [];
for (var i = 0; i < x6.length; i++) {
if (x6[i].indexOf(horas[0]) !== -1) { final.push(x5[i]); }
if (x6[i].indexOf(horas[1]) !== -1) { final.push(x5[i]); }
if (x6[i].indexOf(horas[2]) !== -1) { final.push(x5[i]); }
console.log(final);
}
console.log(final);
A more concise version with a switched Array#indexOf
part.
var horas = ['2', '6'],
x6 = ['1', '2', '3', '4', '5', '6', '7'],
x5 = ['uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete'],
final = [],
i;
for (i = 0; i < x6.length; i++) {
if (horas.indexOf(x6[i]) !== -1) {
final.push(x5[i]);
}
}
console.log(final);
Upvotes: 1
Reputation: 588
Problem in array index while iterating the loop
for (var i = 0; i <= x6.length; i++)
should be changed to
for (var i = 0; i < x6.length; i++)
Upvotes: 1