Paddy
Paddy

Reputation: 37

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()

Upvotes: 3

Views: 2774

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386560

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);

Upvotes: 1

CodeZombie
CodeZombie

Reputation: 2087

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]

Upvotes: 2

Rafael
Rafael

Reputation: 7746

There is certainly a way to do exactly the same thing; it even has similar construction:

let arr = ['a', 'b'];
arr = arr.concat([['c', 'd']]);//['a', 'b', ['c', 'd']]

PHP:

<?php
$arr = ["a", "b"];
$arr[] = ["c", "d"];
print_r($arr);
?>

Array
(
    [0] => a
    [1] => b
    [2] => Array
        (
            [0] => c
            [1] => d
        )
)

Upvotes: 0

Related Questions