Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to merge array[0] and [1] into an integer array in javascript

I have an array named id_list. It has index 0,1

id_list[0]= 200, 201, 202, 203
id_list[1]= 300, 301, 302, 303

I want to merge index[0] and index[1] into an integer array.
I used .join() but it merges all element including , into the array.

var arr = id_list[0].join(id_list[1]);
console.log(arr[0]);  // result => 2
console.log(arr[1]);  // result => 0
console.log(arr[3]);  // result => ,

I just want as id_list= [200, 201, 202, 203, 300, 301, 302, 303].
I don't want the , value.

Please help me how to merge them.

like image 693
Dede Avatar asked Jan 14 '23 02:01

Dede


1 Answers

Your example and the way you're getting individual characters in your results suggests that your values are actually strings, like this:

var id_list = [];
id_list[0] = '200, 201, 202, 203';
id_list[1] = '300, 301, 302, 303';

If that's the case, your first step needs to be converting them to actual arrays. You can do that by just splitting on the , but a regular expression that removes the spaces as well will give you a cleaner result. / *, */ will look for a comma with optional spaces before or after it:

id_list[0] = id_list[0].split(/ *, */);
// now id_list[0] is an array of 4 items: ['200', '201', '202', '203']

id_list[1] = id_list[1].split(/ *, */);
// now id_list[1] is an array of 4 items: ['300', '301', '302', '303']

Then you can use concat() to join your arrays into a single array:

var arr = id_list[0].concat(id_list[1]);

I suspect this is more like the output you're expecting:

console.log(arr[0]); // shows 200
console.log(arr[1]); // shows 201
console.log(arr[3]); // shows 203
console.log(arr[5]); // shows 301
like image 126
jcsanyi Avatar answered Jan 16 '23 18:01

jcsanyi