Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through an array with multiple objects and list certain elements in solely Javascript?

This is the code I have written. I want the listContacts function to loop through the contacts array and log the first and last name of each contact to the console. When I run this though it only logs John Doe to the console. What am I missing here?

var contacts = [ 
  { 
    firstName : 'John',
    lastName : 'Doe',
    phone : '(512) 355-0453',
    email : '[email protected]'
  },
  { 
    firstName : 'Jane',
    lastName : 'Doe',
    phone : '(313) 641-2203',
    email : '[email protected]'
  },
  { 
    firstName : 'Suzie',
    lastName : 'Smith',
    phone : '(415) 604-4219',
    email : '[email protected]'
  }
];  

   var listContacts = function () {
   for (var i = 0; i <= contacts.length; i++) {
   return contacts[i].firstName + ' ' + contacts[i].lastName;
   }
};

console.log(listContacts());
like image 249
gBasgaard Avatar asked May 08 '26 09:05

gBasgaard


1 Answers

Your return statement in your for loop is causing that loop to stop after the first iteration. Instead, you should log within the loop:

var listContacts = function () {
    for (var i = 0; i < contacts.length; i++) {
        console.log(contacts[i].firstName + ' ' + contacts[i].lastName);
    }
}

listContacts();
like image 165
krillgar Avatar answered May 10 '26 22:05

krillgar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!