Reputation: 25
thanks in advance if the array is
var animals = ['Cow', 'Cow', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
how can i get a assoc array like this
// returns {'Cow': 'Moo', 'Cow': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}
Upvotes: 0
Views: 1037
Reputation: 1941
JS Fiddle of all 3 options: http://jsfiddle.net/ysLvfxmd/2/
You want a hash/associative array, loop through and create one by index, however you cannot have duplicate keys in a hash so you may want to explore other data structures.
Pure Hash
var animals = ['Cow', 'Cow', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
var hash = {};
for(i = 0; i < animals.length; i++) {
hash[animals[i]] = sounds[i];
}
console.log(hash);
This will only show Cow once, if you want to have pairs of this with non-unique keys you need to make an array of hashes
Array Of Hashes
var animals = ['Cow', 'Cow', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
var arr = [];
for(i = 0; i < animals.length; i++) {
var hash = {};
hash[animals[i]] = sounds[i];
arr.push(hash);
}
console.log(arr);
However, note that the indexes of the array are now numeric but you can search through it to find your values.
Third Option:
Hash Of Arrays (Best)
//Paul Rob's suggestion hash of arrays
var animals = ['Cow', 'Cow', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
var hashOfArr = [];
for(i = 0; i < animals.length; i++) {
if(!hashOfArr[animals[i]]){
hashOfArr[animals[i]] = [];
}
hashOfArr[animals[i]].push(sounds[i]);
}
console.log(hashOfArr);
Upvotes: 1
Reputation: 33870
What you exactly want is impossible. Objects cannot have multiple keys.
Have an object where the value of each key is an array. If an animal have multiple sound, you'll only have to push it into the array.
var
animals = ['Cow', 'Cow', 'Dog', 'Cat'],
sounds = ['Moo', 'Oink', 'Woof', 'Miao'],
result = {};
for(i = 0; i < animals.length; i++) {
result[animals[i]]
? result[animals[i]].push(sounds[i])
: result[animals[i]] = [sounds[i]];
}
Upvotes: 1