how to insert item in array javascript 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: how to insert an element from an array
int main()
{
int array[100], position, c, n, value;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the location where you wish to insert an element\n");
scanf("%d", &position);
printf("Enter the value to insert\n");
scanf("%d", &value);
for (c = n - 1; c >= position - 1; c--)
array[c+1] = array[c];
array[position-1] = value;
printf("Resultant array is\n");
for (c = 0; c <= n; c++)
printf("%d\n", array[c]);
return 0;
}
Example 3: add item to array javascript
const arr1 = [1,2,3]
const newValue = 4
const newData = [...arr1, obj] // [1,2,3,4]