Reputation: 27
i have a code like this :
function firstArrived(cars) {
// code below here
var yellow = [];
var red = [];
var black = [];
for(var i=0; i <= cars.length; i++){
if(cars[i][1] === 'yellow'){
yellow.push(cars[i][0]);
}
else if(cars[i][1] === 'red'){
red.push(cars[i][0]);
}
else{
black.push(cars[i][0]);
}
}
return yellow;
};
//TEST CASE
console.log(firstArrived([['1171 CA', 'yellow'],['1234', 'black'],['V 76998', 'red']]));
the code is supposed to have a result like this :
[ '1171 CA' ]
but instead, i've got an error like this:
Uncaught TypeError: Cannot read property '1' of undefined
can you help me to find whats wrong in my code? thanks a lot.
Upvotes: 1
Views: 96
Reputation: 386746
If you do not need the other colors than yellow, you could omit these items and take only yellow cars.
Then you need only to iterate without the value of the length, because arrays are zero based and the index of last item is length
- one.
Finally you need not semicolon at the end of a function block of a function declaration.
function firstArrived(cars) {
var yellow = [];
for (var i = 0; i < cars.length; i++) {
if (cars[i][1] === 'yellow') yellow.push(cars[i][0]);
}
return yellow;
}
console.log(firstArrived([['1171 CA', 'yellow'],['1234', 'black'],['V 76998', 'red']]));
Bonus: A loop without indices with for ... of
statement
function firstArrived(cars) {
var yellow = [];
for (var car of cars) {
if (car[1] === 'yellow') yellow.push(car[0]);
}
return yellow;
}
console.log(firstArrived([['1171 CA', 'yellow'],['1234', 'black'],['V 76998', 'red']]));
Upvotes: 1
Reputation: 68933
As array index starts from 0
, with i <= cars.length
you are looping beyond the length of the array. Simply use <
instead of <=
the condition:
for(var i=0; i < cars.length; i++){
function firstArrived(cars) {
// code below here
var yellow = [];
var red = [];
var black = [];
for(var i=0; i < cars.length; i++){
if(cars[i][1] === 'yellow'){
yellow.push(cars[i][0]);
}
else if(cars[i][1] === 'red'){
red.push(cars[i][0]);
}
else{
black.push(cars[i][0]);
}
}
return yellow;
};
//TEST CASE
console.log(firstArrived([['1171 CA', 'yellow'],['1234', 'black'],['V 76998', 'red']]));
Upvotes: 2