3

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

2
  • 1
    No, .push is the shortest/cleanest way to do that Commented Sep 9, 2018 at 14:14
  • 3
    Possible duplicate of Javascript push() shorthand? Commented Sep 9, 2018 at 14:14

3 Answers 3

2

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

1 Comment

This would produce a different result compared to the OP's example, though. This would create a one dimensional array while the OP's example would create a multidimensional array.

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.