1

I have two arrays like so:

arr1 = ['one','two','three']

arr2 = ['1','2','3']

Is there a way with jQuery to combine them so the output would be like:

arr3 = ['one':'1', 'two':'2', 'three':'3']

5
  • 2
    That's not a valid array! Use an object: { key: value } Commented Mar 25, 2015 at 1:57
  • 3
    Why does everyone beg for using jQuery? Commented Mar 25, 2015 at 2:02
  • 1
    Anyway, do you desire an object (per Vohuman) or [[k1,v1],[k2,v2],..] or even ["k1:v1","k2:v2",..] or..? Commented Mar 25, 2015 at 2:04
  • 1
    Thanks user2864740... Just something Im working on. got what i needed below from Scott Stensland Commented Mar 25, 2015 at 2:21
  • 2
    You are looking for Underscore, not jQuery! Commented Mar 25, 2015 at 3:01

3 Answers 3

1

I believe you are asking to create an object (associative array) if so

var arr1 = ['one','two','three'];

var arr2 = ['1','2','3'];

var combo_obj = {};

arr1.forEach(function(element, index) {

    combo_obj[element] = arr2[index];
});

console.log(combo_obj);

here is its output

{ one: '1', two: '2', three: '3' }
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, your correct. I was looking to create an object . Apologies for the typo thank you...
1
var result = {};
for(i=0; i< arr1.length && i < arr2.length; ++i){
    result[arr1[i]] = arr2[i];
}

Comments

0

Yes. Check here: Combaining two array into single multi dimensional array in javascript

Here is an example:

arr3=[];
for (i = 0; i < arr2.length; ++i)
{
    arr3[i] = Array(arr1[i], arr2[i]);
}

Comments

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.