7

How can I associate two arrays that contains keys and values into one array with key->value pairs?

In Mootools there is associate function which does:

var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
sounds.associate(animals);
// returns {'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}

Is there any similar function in JQuery to obtain the same result from those two arrays?

If not, how can I do it?

tzortzik
  • 4,993
  • 9
  • 57
  • 88
  • MooTools has much more non-DOM methods than jQuery. You could use MooTools instead of jQuery... then you have all DOM methods from MooTools, plus the extra sugar like this `.associate()` method. – Sergio May 28 '14 at 12:21

7 Answers7

6

JavaScript doesn't really have associative arrays, but you can use an object instead.

Array.prototype.associate = function (keys) {
  var result = {};

  this.forEach(function (el, i) {
    result[keys[i]] = el;
  });

  return result;
};

var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
console.dir(sounds.associate(animals));
Korikulum
  • 2,529
  • 21
  • 25
  • if i have a duplicate values in animals array and i want to append this value with previous (let say in Array) value, it returns a number instead of value. var animals = ['Cow', 'Pig', 'Dog', 'Cow']; var sounds = ['Moo', 'Oink', 'Woof', 'Miao']; – hitttt Dec 07 '18 at 07:46
2

You can use Array.prototype.reduce

var keys = ['a', 'b', 'c'],
    values = [1, 2, 3],
    associated = keys.reduce(function (previous, key, index) {
        previous[key] = values[index];
        return previous
    }, {})

console.log(associated) // Object {a: 1, b: 2, c: 3} 

reduce is not supported natively on IE<9 but you can safely use the Polyfill on the mdn site which you can include using a conditional comment to target ie <9 only.

If you want a reusable function is pretty straightforward to do:

function associate(keys, values){
    return keys.reduce(function (previous, key, index) {
        previous[key] = values[index];
        return previous
    }, {})
} 
kentaromiura
  • 6,459
  • 2
  • 21
  • 15
1

Not jQuery, but simple enough to be achieved with pure JS (here's a fiddle):

var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
var assoc = [];
for(var i=0; i<animals.length; i++) {
    assoc[animals[i]] = sounds[i];
}
console.log(assoc);

prints:

Cat: "Miao"
Cow: "Moo"
Dog: "Woof"
Pig: "Oink"
MCL
  • 3,985
  • 3
  • 27
  • 39
1

You could write your own similar to this:

Array.prototype.associate = function(arr){
    var index,
        output = Object.create(null);

    for(index = 0; index < this.length; index++){
        output[arr[index]] = this[index];
    }

    return output;
};

Then you can use it as expected, similar to this:

var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
var x = sounds.associate(animals);

The result in x is {'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}


DEMO - Replicating Mootool's associate function


Nope
  • 22,147
  • 7
  • 47
  • 72
0

you can use in java scipt.

Array.prototype.associate= function(){
 var that = this;
 var associated ={};
 var len = that.length;
 for(var i=0; i < len; i++){
    associated[that[i]] = value[i];
 }
 return associated;
 } 
var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
console.log(animals.associate(sounds));
Maneesh Singh
  • 555
  • 2
  • 12
0

If you can add a dependency like lodash to your project, then it's as easy as:

let result = _.zip([key1, key2], [value1, value2])

This will produce a new array of arrays:

[[key1, value1], [key2, value2]]

To the result, apply the lodash function fromPairs:

let finalResult = _.fromPairs(resultArrayFromPreviousCode)

finalResult is now:

{ key1: value1, key2: value2 }

Hope that helps!

chesscov77
  • 770
  • 8
  • 14
0

for...of Method

You can also use a for...of statement in conjunction with Array.prototype.entries() to create an object using one array for keys and another for values:

const array_combine = (keys, values) => {
  const result = {};
  
  for (const [index, key] of keys.entries()) {
    result[key] = values[index];
  }
  
  return result;
};

const animals = ['Cow', 'Pig', 'Dog', 'Cat'];
const sounds  = ['Moo', 'Oink', 'Woof', 'Miao'];

console.log(array_combine(animals, sounds));
Community
  • 1
  • 1
Grant Miller
  • 27,532
  • 16
  • 147
  • 165