1

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.

2 Answers 2

2

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']]));

Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much man, turns out it just because " = " problem.. its solved now,, once again, thanks :)
1

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']]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.