-1

I apologise if this question has already been asked on here before but I cant find it.

Im having trouble merging two arrays together and im an absolute beginner with javascript.

I need to do this in pure javascript and not use any library code.

Here is the code;

var greetings = [
  'Hello',
  'Bonjour',
  'Ola',
],

names = {
  'One': 'Bill',
  'Two': 'John',
  'Three': 'Paul',
};

What I would like the result to appear as would be the following in an unordered list as well as each statement being in there own seperate list item;

<ul>
   <li>Hello Bill</li><br/>
   <li>Bonjour John</li><br/>
   <li>Ola Paul</li><br/>
</ul>

If anyone could answer this question, as well as comment the code so I can understand how it works that would be perfect.

Wayne
  • 59,728
  • 15
  • 131
  • 126
PI.
  • 1,658
  • 4
  • 19
  • 33
  • 2
    See http://stackoverflow.com/questions/929776/merging-associative-arrays-javascript – Russ Clarke Jul 19 '11 at 22:13
  • You have an Object and an Array. This will give you troubles because you can't guarantee the order when enumerating the Object. – user113716 Jul 19 '11 at 22:16
  • @Russ C: Take another look at the question. OP appears to be trying to associate the content of the items in one with the items in the other. – user113716 Jul 19 '11 at 22:19

5 Answers5

2

You can not guarantee the order of enumeration when using a for-in statement.

As such, you'd need to have a separate array that specifies the order.

var greetings = [
  'Hello',
  'Bonjour',
  'Ola',
],

names = {
  'One': 'Bill',
  'Two': 'John',
  'Three': 'Paul',
},

order = [
   'One',
   'Two',
   'Three'
], 

items = [];

for( var i = 0, len = order.length; i < len; i++ ) {
   items.push( greetings[i] + ' ' + names[ order[i] ] );
}

document.body.innerHTML = ( "<ul><li>" + items.join("</li><li>") + "</li></ul>" );

But this would be a pain. You should use 2 Arrays instead.

Example: http://jsfiddle.net/rktyF/1/

EDIT: I got rid of the <br> since it's unnecessary.

user113716
  • 318,772
  • 63
  • 451
  • 440
  • Hi there, thats awesome, Is it possible to expand on that and show me how you would contain each statement inside a
  • which can then be pushed into a
      .... very grateful
  • – PI. Jul 19 '11 at 22:30
  • @user: You're welcome, but can you use 2 Arrays, instead of an Array and an object literal? – user113716 Jul 19 '11 at 22:34
  • Not really, its a task ive been set for my training which i was having problems with .... thanks again – PI. Jul 19 '11 at 22:38