add arrays javascript code example

Example 1: javascript append to array

var colors=["red","white"];
colors.push("blue");//append 'blue' to colors

Example 2: append array js

var colors= ["red","blue"];
	colors.push("yellow"); //["red","blue","yellow"]

Example 3: merge array in js

//for ES5
var array1 = ["Rahul", "Sachin"];
var array2 = ["Sehwag", "Kohli"];

var output = array1.concat(array2);
console.log(output);

//for ES6, we use spread operators to concat arrays

var array1 = ["Dravid", "Tendulkar"];
var array2 = ["Virendra", "Virat"];

var output = [...array1, ...array2];
console.log(output);

Example 4: add array to array javascript

// SPREAD OPERATOR
 const list1 = ["pepe", "luis", "rua"];
 const list2 = ["rojo", "verde", "azul"];
 const newList = [...list1, ...list2];
 // ["pepe", "luis", "rua", "rojo", "verde", "azul"]

Example 5: array insertion javascript

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};

Example 6: concat js mdn

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

Tags:

Java Example