Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function 'concat' (in JavaScript) is not working for associative arrays

I have a problem concatenating two associative arrays in JavaScript. Below is the sample code:

var firstArray =  new Array();
firstArray.c1 = "sam";
firstArray.c2 = "kam";
var secArray =  new Array();
secArray.c3 = "sam";
secArray.c4 = "kam";
var res = firstArray.concat(secArray);

Is this a known limitation?

What's the best way to achieve this?

like image 329
RameshVel Avatar asked Aug 20 '09 11:08

RameshVel


2 Answers

You are not using Array functionality - just Object functionality. In JavaScript, Object is an associative array - you use Array for arrays indexed by integers. If you did

var firstArray =  new Array();
firstArray.push("sam");  
firstArray.push("kam");
var secArray =  new Array();
secArray.push("sam");    
secArray.push("kam");
var res = firstArray.concat(secArray);

then concat would work as expected.

If you actually want to merge associative arrays, do:

for (var attr in src_array) { dest_array[attr] = src_array[attr]; }

This will of course overwrite existing keys in dest_array which have counterparts in src_array.

like image 57
Vinay Sajip Avatar answered Oct 15 '22 03:10

Vinay Sajip


Try this:

var firstArray = new Array("sam", "kam");
var secArray = new Array("sam", "kam");
var res = firstArray.concat(secArray);
like image 28
kayteen Avatar answered Oct 15 '22 05:10

kayteen