Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Auto Increment Array

Is there a shorthand way to auto increment a Javascript array like you can in PHP?

PHP Example:

$myArray=[];
$myArray[] = [ 'item1' , 'item2' ];
$myArray[] = [ 'item3' , 'item4' ];

JS Example:

let myArray = [];
myArray[ myArray.length ] = [ 'item1' , 'item2' ];
myArray[ myArray.length ] = [ 'item3' , 'item4 '];
//or
myArray.push( [ 'item1' , 'item2' ] );
myArray.push( [ 'item3' , 'item4' ] );

Without using myArray.length or myArray.push()

like image 272
Paddy Avatar asked Aug 04 '26 11:08

Paddy


2 Answers

Here is the ES6 way, using spread operator

const arr1 = [1,2,3];
const arr2 = [3,4,5];
const arr3 = [...arr1, ...arr2]; // arr3 ==> [1,2,3,3,4,5]

OR

just by using the concat method

const arr1 = [1,2,3];
const arr2 = [3,4,5];
const arr3 = arr1.concat(arr2); // arr3 ==> [1,2,3,3,4,5]
like image 106
CodeZombie Avatar answered Aug 06 '26 01:08

CodeZombie


Beside the given answers, you could use Array#splice with a great value for adding the values to the end of the array.

var array = [];

array.splice(Infinity, 0, ...['item1', 'item2']);
array.splice(Infinity, 0, ...['item3', 'item4']);

console.log(array);
like image 22
Nina Scholz Avatar answered Aug 06 '26 03:08

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!