add items to an array code example

Example 1: javascript insert item into array

var colors=["red","blue"];
var index=1;

//insert "white" at index 1
colors.splice(index, 0, "white");   //colors =  ["red", "white", "blue"]

Example 2: javascript append to array

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

Example 3: append array js

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

Example 4: javascript pushing to an array

some_array = ["John", "Sally"];
some_array.push("Mike");

console.log(some_array); //output will be =>
["John", "Sally", "Mike"]

Example 5: add value to array javascript

var fruits = ["222", "vvvv", "eee", "eeee"];

fruits.push("Kiwi");

Example 6: js add to array

const myArray = ['hello', 'world'];

// add an element to the end of the array
myArray.push('foo'); // ['hello', 'world', 'foo']

// add an element to the front of the array
myArray.unshift('bar'); // ['bar', 'hello', 'world', 'foo']

// add an element at an index of your choice
// the first value is the index you want to add at
// the second value is how many you want to delete (0 in this case)
// the third value is the value you want to insert
myArray.splice(2, 0, 'there'); // ['bar', 'hello', 'there', 'world', 'foo']

Tags:

Misc Example