0

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'}
2
  • 2
    You mean "Pig" for the second "Cow", right? You can't have an object with two identical keys. Commented Dec 4, 2014 at 13:57
  • How? Write an algorithm and code it. Nobody here will code it for you. That's not the purpose of SO. Commented Dec 4, 2014 at 13:58

2 Answers 2

1

Short answer

What you exactly want is impossible. Objects cannot have multiple keys.

My suggestion

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]];
}

Fiddle

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

Comments

1

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

2 Comments

Seems more sensible to go with a hash of arrays, e.g. { 'Cow':['Moo', 'Oink'], 'Dog': ['Woof'], 'Cat': ['Miao'] }
I was thinking the same thing after I wrote it, let me add another example for that

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.