Add two arrays without using the concat method - javascript

Here is a sample of what I would like to do
function test(r){
var arr = ['d','e','f'];
r.push(arr);
/*
More Code
*/
return r;
}
var result = test(['a','b','c']);
alert(result.length);//I want this to alert 6
What I need to do is pass in an array and attach other arrays to the end of it and then return the array. Because of passing by reference I cannot use array.concat(array2);. Is there a way to do this without using something like a for loop to add the elements one by one. I tried something like r.push(arr.join()); but that did not work either. Also, I would like the option of having objects in the arrays so really the r.push(arr.join()); doesn't work very well.

>>> var x = [1, 2, 3], y = [4, 5, 6];
>>> x.push.apply(x, y) // or Array.prototype.push.apply(x, y)
>>> x
[1, 2, 3, 4, 5, 6]
Alternatively using destructuring you can now do this
//generate a new array
a=[...x,...y];
//or modify one of the original arrays
x.push(...y);

function test(r){
var _r = r.slice(0), // copy to new array reference
arr = ['d','e','f'];
_r = _r.concat(arr); // can use concat now
return _r;
}
var result = test(['a','b','c']);
alert(result.length); // 6

This is emulbreh's answer, I'm just posting the test I did to verify it.
All credit should go to emulbreh
// original array
var r = ['a','b','c'];
function test(r){
var arr = ['d','e','f'];
r.push.apply(r, arr);
/*
More Code
*/
return r;
}
var result = test( r );
console.log( r ); // ["a", "b", "c", "d", "e", "f"]
console.log( result === r ); // the returned array IS the original array but modified

Related

forEach number to a new array rather than a list [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How do I append an object (such as a string or number) to an array in JavaScript?
Use the Array.prototype.push method to append values to the end of an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);
You can use the push() function to append more than one value to an array in a single call:
// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];
// append multiple values to the array
arr.push("Salut", "Hey");
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Update
If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):
var arr = [
"apple",
"banana",
"cherry"
];
// Do not forget to assign the result as, unlike push, concat does not change the existing array
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
Update
Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.
var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);
It also supports appending multiple values at once just like push.
Update
Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.
const arr = [
"Hi",
"Hello",
"Bonjour",
];
const newArr = [
...arr,
"Salut",
];
console.log(newArr);
If you're only appending a single variable, then push() works just fine. If you need to append another array, use concat():
var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
var ar3 = ar1.concat(ar2);
alert(ar1);
alert(ar2);
alert(ar3);
The concat does not affect ar1 and ar2 unless reassigned, for example:
var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
ar1 = ar1.concat(ar2);
alert(ar1);
There is a lot of great information on JavaScript Reference.
Some quick benchmarking (each test = 500k appended elements and the results are averages of multiple runs) showed the following:
Firefox 3.6 (Mac):
Small arrays: arr[arr.length] = b is faster (300ms vs. 800ms)
Large arrays: arr.push(b) is faster (500ms vs. 900ms)
Safari 5.0 (Mac):
Small arrays: arr[arr.length] = b is faster (90ms vs. 115ms)
Large arrays: arr[arr.length] = b is faster (160ms vs. 185ms)
Google Chrome 6.0 (Mac):
Small arrays: No significant difference (and Chrome is FAST! Only ~38ms !!)
Large arrays: No significant difference (160ms)
I like the arr.push() syntax better, but I think I'd be better off with the arr[arr.length] Version, at least in raw speed. I'd love to see the results of an IE run though.
My benchmarking loops:
function arrpush_small() {
var arr1 = [];
for (a = 0; a < 100; a++)
{
arr1 = [];
for (i = 0; i < 5000; i++)
{
arr1.push('elem' + i);
}
}
}
function arrlen_small() {
var arr2 = [];
for (b = 0; b < 100; b++)
{
arr2 = [];
for (j = 0; j < 5000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}
}
function arrpush_large() {
var arr1 = [];
for (i = 0; i < 500000; i++)
{
arr1.push('elem' + i);
}
}
function arrlen_large() {
var arr2 = [];
for (j = 0; j < 500000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}
I think it's worth mentioning that push can be called with multiple arguments, which will be appended to the array in order. For example:
var arr = ['first'];
arr.push('second', 'third');
console.log(arr);
As a result of this you can use push.apply to append an array to another array like so:
var arr = ['first'];
arr.push('second', 'third');
arr.push.apply(arr, ['forth', 'fifth']);
console.log(arr);
Annotated ES5 has more info on exactly what push and apply do.
2016 update: with spread, you don't need that apply anymore, like:
var arr = ['first'];
arr.push('second', 'third');
arr.push(...['fourth', 'fifth']);
console.log(arr) ;
You can use the push and apply functions to append two arrays.
var array1 = [11, 32, 75];
var array2 = [99, 67, 34];
Array.prototype.push.apply(array1, array2);
console.log(array1);
It will append array2 to array1. Now array1 contains [11, 32, 75, 99, 67, 34].
This code is much simpler than writing for loops to copy each and every items in the array.
With the new ES6 spread operator, joining two arrays using push becomes even easier:
var arr = [1, 2, 3, 4, 5];
var arr2 = [6, 7, 8, 9, 10];
arr.push(...arr2);
console.log(arr);
This adds the contents of arr2 onto the end of arr.
Babel REPL Example
If arr is an array, and val is the value you wish to add use:
arr.push(val);
E.g.
var arr = ['a', 'b', 'c'];
arr.push('d');
console.log(arr);
Use concat:
a = [1, 2, 3];
b = [3, 4, 5];
a = a.concat(b);
console.log(a);
JavaScript with the ECMAScript 5 (ES5) standard which is supported by most browsers now, you can use apply() to append array1 to array2.
var array1 = [3, 4, 5];
var array2 = [1, 2];
Array.prototype.push.apply(array2, array1);
console.log(array2); // [1, 2, 3, 4, 5]
JavaScript with ECMAScript 6 (ES6) standard which is supported by Chrome, Firefox, Internet Explorer, and Edge, you can use the spread operator:
"use strict";
let array1 = [3, 4, 5];
let array2 = [1, 2];
array2.push(...array1);
console.log(array2); // [1, 2, 3, 4, 5]
The spread operator will replace array2.push(...array1); with array2.push(3, 4, 5); when the browser is thinking the logic.
Bonus point
If you'd like to create another variable to store all the items from both arrays, you can do this:
ES5 var combinedArray = array1.concat(array2);
ES6 const combinedArray = [...array1, ...array2]
The spread operator (...) is to spread out all items from a collection.
If you want to append two arrays -
var a = ['a', 'b'];
var b = ['c', 'd'];
then you could use:
var c = a.concat(b);
And if you want to add record g to array (var a=[]) then you could use:
a.push('g');
There are a couple of ways to append an array in JavaScript:
1) The push() method adds one or more elements to the end of an array and returns the new length of the array.
var a = [1, 2, 3];
a.push(4, 5);
console.log(a);
Output:
[1, 2, 3, 4, 5]
2) The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array:
var a = [1, 2, 3];
a.unshift(4, 5);
console.log(a);
Output:
[4, 5, 1, 2, 3]
3) The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var arr1 = ["a", "b", "c"];
var arr2 = ["d", "e", "f"];
var arr3 = arr1.concat(arr2);
console.log(arr3);
Output:
[ "a", "b", "c", "d", "e", "f" ]
4) You can use the array's .length property to add an element to the end of the array:
var ar = ['one', 'two', 'three'];
ar[ar.length] = 'four';
console.log( ar );
Output:
["one", "two", "three", "four"]
5) The splice() method changes the content of an array by removing existing elements and/or adding new elements:
var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(4, 0, "nemo");
//array.splice(start, deleteCount, item1, item2, ...)
console.log(myFish);
Output:
["angel", "clown", "mandarin", "surgeon","nemo"]
6) You can also add a new element to an array simply by specifying a new index and assigning a value:
var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar
console.log(ar);
Output:
["one", "two","three","four"]
The push() method adds new items to the end of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
// The result of fruits will be:
Banana, Orange, Apple, Mango, Kiwi
The exact answer to your question is already answered, but let's look at some other ways to add items to an array.
The unshift() method adds new items to the beginning of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");
// The result of fruits will be:
Lemon, Pineapple, Banana, Orange, Apple, Mango
And lastly, the concat() method is used to join two or more arrays. Example:
var fruits = ["Banana", "Orange"];
var moreFruits = ["Apple", "Mango", "Lemon"];
var allFruits = fruits.concat(moreFruits);
// The values of the children array will be:
Banana, Orange, Apple, Mango, Lemon
Now, you can take advantage of ES6 syntax and just do
let array = [1, 2];
console.log([...array, 3]);
keeping the original array immutable.
Append a single element
// Append to the end
arrName.push('newName1');
// Prepend to the start
arrName.unshift('newName1');
// Insert at index 1
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element
// Replace index 3 (of exists), add new element otherwise.
arrName[3] = 'newName1';
Append multiple elements
// Insert from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where insert starts,
// 0: number of element to remove,
//newElemenet1,2,3: new elements
Append an array
// Join two or more arrays
arrName.concat(newAry1, newAry2);
//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array
If you know the highest index (such as stored in a variable "i") then you can do
myArray[i + 1] = someValue;
However, if you don't know then you can either use
myArray.push(someValue);
as other answers suggested, or you can use
myArray[myArray.length] = someValue;
Note that the array is zero based so .length returns the highest index plus one.
Also note that you don't have to add in order and you can actually skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined.
It is therefore a good practice when looping through a JavaScript to verify that a value actually exists at that point.
This can be done by something like the following:
if(myArray[i] === "undefined"){ continue; }
If you are certain that you don't have any zeros in the array then you can just do:
if(!myArray[i]){ continue; }
Of course, make sure in this case that you don't use as the condition myArray[i] (as some people over the Internet suggest based on the end that as soon as i is greater than the highest index, it will return undefined which evaluates to false).
You can do it using JavaScript Spread Operator Syntax:
// Initialize the array
var arr = [
"Hi",
"Hello",
"Bangladesh"
];
// Append a new value to the array
arr = [...arr, "Feni"];
// Or you can add a variable value
var testValue = "Cool";
arr = [...arr, testValue ];
console.log(arr);
// Final output [ 'Hi', 'Hello', 'Bangladesh', 'Feni', 'Cool' ]
If you are using ES6 you can use spread operator to do it.
var arr = [
"apple",
"banana",
"cherry"
];
var arr2 = [
"dragonfruit",
"elderberry",
"fig"
];
arr.push(...arr2);
concat(), of course, can be used with two-dimensional arrays as well. No looping required.
var a = [
[1, 2],
[3, 4] ];
var b = [
["a", "b"],
["c", "d"] ];
b = b.concat(a);
alert(b[2][1]); // Result: 2
Just want to add a snippet for non-destructive addition of an element.
var newArr = oldArr.concat([newEl]);
Let the array length property do the work:
myarray[myarray.length] = 'new element value added to the end of the array';
myarray.length returns the number of strings in the array.
JavaScript is zero-based, so the next element key of the array will be the current length of the array.
Example:
var myarray = [0, 1, 2, 3],
myarrayLength = myarray.length; // myarrayLength is set to 4
Append a value to an array
Since Array.prototype.push adds one or more elements to the end of an array and returns the new length of the array, sometimes we want just to get the new up-to-date array so we can do something like so:
const arr = [1, 2, 3];
const val = 4;
arr.concat([val]); // [1, 2, 3, 4]
Or just:
[...arr, val] // [1, 2, 3, 4]
Append a single item
To append a single item to an array, use the push() method provided by the Array object:
const fruits = ['banana', 'pear', 'apple']
fruits.push('mango')
console.log(fruits)
push() mutates the original array.
To create a new array instead, use the concat() Array method:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')
console.log(allfruits)
Notice that concat() does not actually add an item to the array, but creates a new array, which you can assign to another variable, or reassign to the original array (declaring it as let, as you cannot reassign a const):
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')
console.log(allfruits)
let fruits = ['banana', 'pear', 'apple']
fruits = fruits.concat('mango')
Append multiple items
To append a multiple item to an array, you can use push() by calling it with multiple arguments:
const fruits = ['banana', 'pear', 'apple']
fruits.push('mango', 'melon', 'avocado')
console.log(fruits)
You can also use the concat() method you saw before, passing a list of items separated by a comma:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango', 'melon', 'avocado')
console.log(allfruits)
or an array:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat(['mango', 'melon', 'avocado'])
console.log(allfruits)
Remember that as described previously this method does not mutate the original array, but it returns a new array.
Originally posted at
If you want to combine two arrays without the duplicate you may try the code below:
array_merge = function (arr1, arr2) {
return arr1.concat(arr2.filter(function(item){
return arr1.indexOf(item) < 0;
}))
}
Usage:
array1 = ['1', '2', '3']
array2 = ['2', '3', '4', '5']
combined_array = array_merge(array1, array2)
Output:
[1,2,3,4,5]
You .push() that value in.
Example: array.push(value);
If you want to append a single value into an array, simply use the push method. It will add a new element at the end of the array.
But if you intend to add multiple elements then store the elements in a new array and concat the second array with the first array...either way you wish.
arr=['a','b','c'];
arr.push('d');
//now print the array in console.log and it will contain 'a','b','c','d' as elements.
console.log(array);
We don't have an append function for Array in JavaScript, but we have push and unshift. Imagine you have the array below:
var arr = [1, 2, 3, 4, 5];
And we like to append a value to this array. We can do arr.push(6), and it will add 6 to the end of the array:
arr.push(6); // Returns [1, 2, 3, 4, 5, 6];
Also we can use unshift, look at how we can apply this:
arr.unshift(0); // Returns [0, 1, 2, 3, 4, 5];
They are main functions to add or append new values to the arrays.
You can use the push() if you want to add values,
e.g. arr.push("Test1", "Test2");.
If you have array you can use concat(), e.g. Array1.concat(Array2).
If you have just one element to add, you can also try the length method, e.g. array[aray.length] = 'test';.
Appending items on an array
let fruits = ["orange", "banana", "apple", "lemon"]; /* Array declaration */
fruits.push("avacado"); /* Adding an element to the array */
/* Displaying elements of the array */
for(var i=0; i < fruits.length; i++){
console.log(fruits[i]);
}
You can use the push method.
Array.prototype.append = function(destArray){
destArray = destArray || [];
this.push.call(this, ...destArray);
return this;
}
var arr = [1,2,5,67];
var arr1 = [7,4,7,8];
console.log(arr.append(arr1)); // [7, 4, 7, 8, 1, 4, 5, 67, 7]
console.log(arr.append("Hola")) // [1, 2, 5, 67, 7, 4, 7, 8, "H", "o", "l", "a"]
push() adds a new element to the end of an array.
pop() removes an element from the end of an array.
To append an object (such as a string or number) to an array, use:
array.push(toAppend);

How to add items to an object inside a javascript array? [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How do I append an object (such as a string or number) to an array in JavaScript?
Use the Array.prototype.push method to append values to the end of an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);
You can use the push() function to append more than one value to an array in a single call:
// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];
// append multiple values to the array
arr.push("Salut", "Hey");
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Update
If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):
var arr = [
"apple",
"banana",
"cherry"
];
// Do not forget to assign the result as, unlike push, concat does not change the existing array
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
Update
Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.
var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);
It also supports appending multiple values at once just like push.
Update
Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.
const arr = [
"Hi",
"Hello",
"Bonjour",
];
const newArr = [
...arr,
"Salut",
];
console.log(newArr);
If you're only appending a single variable, then push() works just fine. If you need to append another array, use concat():
var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
var ar3 = ar1.concat(ar2);
alert(ar1);
alert(ar2);
alert(ar3);
The concat does not affect ar1 and ar2 unless reassigned, for example:
var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
ar1 = ar1.concat(ar2);
alert(ar1);
There is a lot of great information on JavaScript Reference.
Some quick benchmarking (each test = 500k appended elements and the results are averages of multiple runs) showed the following:
Firefox 3.6 (Mac):
Small arrays: arr[arr.length] = b is faster (300ms vs. 800ms)
Large arrays: arr.push(b) is faster (500ms vs. 900ms)
Safari 5.0 (Mac):
Small arrays: arr[arr.length] = b is faster (90ms vs. 115ms)
Large arrays: arr[arr.length] = b is faster (160ms vs. 185ms)
Google Chrome 6.0 (Mac):
Small arrays: No significant difference (and Chrome is FAST! Only ~38ms !!)
Large arrays: No significant difference (160ms)
I like the arr.push() syntax better, but I think I'd be better off with the arr[arr.length] Version, at least in raw speed. I'd love to see the results of an IE run though.
My benchmarking loops:
function arrpush_small() {
var arr1 = [];
for (a = 0; a < 100; a++)
{
arr1 = [];
for (i = 0; i < 5000; i++)
{
arr1.push('elem' + i);
}
}
}
function arrlen_small() {
var arr2 = [];
for (b = 0; b < 100; b++)
{
arr2 = [];
for (j = 0; j < 5000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}
}
function arrpush_large() {
var arr1 = [];
for (i = 0; i < 500000; i++)
{
arr1.push('elem' + i);
}
}
function arrlen_large() {
var arr2 = [];
for (j = 0; j < 500000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}
I think it's worth mentioning that push can be called with multiple arguments, which will be appended to the array in order. For example:
var arr = ['first'];
arr.push('second', 'third');
console.log(arr);
As a result of this you can use push.apply to append an array to another array like so:
var arr = ['first'];
arr.push('second', 'third');
arr.push.apply(arr, ['forth', 'fifth']);
console.log(arr);
Annotated ES5 has more info on exactly what push and apply do.
2016 update: with spread, you don't need that apply anymore, like:
var arr = ['first'];
arr.push('second', 'third');
arr.push(...['fourth', 'fifth']);
console.log(arr) ;
You can use the push and apply functions to append two arrays.
var array1 = [11, 32, 75];
var array2 = [99, 67, 34];
Array.prototype.push.apply(array1, array2);
console.log(array1);
It will append array2 to array1. Now array1 contains [11, 32, 75, 99, 67, 34].
This code is much simpler than writing for loops to copy each and every items in the array.
With the new ES6 spread operator, joining two arrays using push becomes even easier:
var arr = [1, 2, 3, 4, 5];
var arr2 = [6, 7, 8, 9, 10];
arr.push(...arr2);
console.log(arr);
This adds the contents of arr2 onto the end of arr.
Babel REPL Example
If arr is an array, and val is the value you wish to add use:
arr.push(val);
E.g.
var arr = ['a', 'b', 'c'];
arr.push('d');
console.log(arr);
Use concat:
a = [1, 2, 3];
b = [3, 4, 5];
a = a.concat(b);
console.log(a);
JavaScript with the ECMAScript 5 (ES5) standard which is supported by most browsers now, you can use apply() to append array1 to array2.
var array1 = [3, 4, 5];
var array2 = [1, 2];
Array.prototype.push.apply(array2, array1);
console.log(array2); // [1, 2, 3, 4, 5]
JavaScript with ECMAScript 6 (ES6) standard which is supported by Chrome, Firefox, Internet Explorer, and Edge, you can use the spread operator:
"use strict";
let array1 = [3, 4, 5];
let array2 = [1, 2];
array2.push(...array1);
console.log(array2); // [1, 2, 3, 4, 5]
The spread operator will replace array2.push(...array1); with array2.push(3, 4, 5); when the browser is thinking the logic.
Bonus point
If you'd like to create another variable to store all the items from both arrays, you can do this:
ES5 var combinedArray = array1.concat(array2);
ES6 const combinedArray = [...array1, ...array2]
The spread operator (...) is to spread out all items from a collection.
If you want to append two arrays -
var a = ['a', 'b'];
var b = ['c', 'd'];
then you could use:
var c = a.concat(b);
And if you want to add record g to array (var a=[]) then you could use:
a.push('g');
There are a couple of ways to append an array in JavaScript:
1) The push() method adds one or more elements to the end of an array and returns the new length of the array.
var a = [1, 2, 3];
a.push(4, 5);
console.log(a);
Output:
[1, 2, 3, 4, 5]
2) The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array:
var a = [1, 2, 3];
a.unshift(4, 5);
console.log(a);
Output:
[4, 5, 1, 2, 3]
3) The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var arr1 = ["a", "b", "c"];
var arr2 = ["d", "e", "f"];
var arr3 = arr1.concat(arr2);
console.log(arr3);
Output:
[ "a", "b", "c", "d", "e", "f" ]
4) You can use the array's .length property to add an element to the end of the array:
var ar = ['one', 'two', 'three'];
ar[ar.length] = 'four';
console.log( ar );
Output:
["one", "two", "three", "four"]
5) The splice() method changes the content of an array by removing existing elements and/or adding new elements:
var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(4, 0, "nemo");
//array.splice(start, deleteCount, item1, item2, ...)
console.log(myFish);
Output:
["angel", "clown", "mandarin", "surgeon","nemo"]
6) You can also add a new element to an array simply by specifying a new index and assigning a value:
var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar
console.log(ar);
Output:
["one", "two","three","four"]
The push() method adds new items to the end of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
// The result of fruits will be:
Banana, Orange, Apple, Mango, Kiwi
The exact answer to your question is already answered, but let's look at some other ways to add items to an array.
The unshift() method adds new items to the beginning of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");
// The result of fruits will be:
Lemon, Pineapple, Banana, Orange, Apple, Mango
And lastly, the concat() method is used to join two or more arrays. Example:
var fruits = ["Banana", "Orange"];
var moreFruits = ["Apple", "Mango", "Lemon"];
var allFruits = fruits.concat(moreFruits);
// The values of the children array will be:
Banana, Orange, Apple, Mango, Lemon
Now, you can take advantage of ES6 syntax and just do
let array = [1, 2];
console.log([...array, 3]);
keeping the original array immutable.
Append a single element
// Append to the end
arrName.push('newName1');
// Prepend to the start
arrName.unshift('newName1');
// Insert at index 1
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element
// Replace index 3 (of exists), add new element otherwise.
arrName[3] = 'newName1';
Append multiple elements
// Insert from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where insert starts,
// 0: number of element to remove,
//newElemenet1,2,3: new elements
Append an array
// Join two or more arrays
arrName.concat(newAry1, newAry2);
//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array
If you know the highest index (such as stored in a variable "i") then you can do
myArray[i + 1] = someValue;
However, if you don't know then you can either use
myArray.push(someValue);
as other answers suggested, or you can use
myArray[myArray.length] = someValue;
Note that the array is zero based so .length returns the highest index plus one.
Also note that you don't have to add in order and you can actually skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined.
It is therefore a good practice when looping through a JavaScript to verify that a value actually exists at that point.
This can be done by something like the following:
if(myArray[i] === "undefined"){ continue; }
If you are certain that you don't have any zeros in the array then you can just do:
if(!myArray[i]){ continue; }
Of course, make sure in this case that you don't use as the condition myArray[i] (as some people over the Internet suggest based on the end that as soon as i is greater than the highest index, it will return undefined which evaluates to false).
You can do it using JavaScript Spread Operator Syntax:
// Initialize the array
var arr = [
"Hi",
"Hello",
"Bangladesh"
];
// Append a new value to the array
arr = [...arr, "Feni"];
// Or you can add a variable value
var testValue = "Cool";
arr = [...arr, testValue ];
console.log(arr);
// Final output [ 'Hi', 'Hello', 'Bangladesh', 'Feni', 'Cool' ]
If you are using ES6 you can use spread operator to do it.
var arr = [
"apple",
"banana",
"cherry"
];
var arr2 = [
"dragonfruit",
"elderberry",
"fig"
];
arr.push(...arr2);
concat(), of course, can be used with two-dimensional arrays as well. No looping required.
var a = [
[1, 2],
[3, 4] ];
var b = [
["a", "b"],
["c", "d"] ];
b = b.concat(a);
alert(b[2][1]); // Result: 2
Just want to add a snippet for non-destructive addition of an element.
var newArr = oldArr.concat([newEl]);
Let the array length property do the work:
myarray[myarray.length] = 'new element value added to the end of the array';
myarray.length returns the number of strings in the array.
JavaScript is zero-based, so the next element key of the array will be the current length of the array.
Example:
var myarray = [0, 1, 2, 3],
myarrayLength = myarray.length; // myarrayLength is set to 4
Append a value to an array
Since Array.prototype.push adds one or more elements to the end of an array and returns the new length of the array, sometimes we want just to get the new up-to-date array so we can do something like so:
const arr = [1, 2, 3];
const val = 4;
arr.concat([val]); // [1, 2, 3, 4]
Or just:
[...arr, val] // [1, 2, 3, 4]
Append a single item
To append a single item to an array, use the push() method provided by the Array object:
const fruits = ['banana', 'pear', 'apple']
fruits.push('mango')
console.log(fruits)
push() mutates the original array.
To create a new array instead, use the concat() Array method:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')
console.log(allfruits)
Notice that concat() does not actually add an item to the array, but creates a new array, which you can assign to another variable, or reassign to the original array (declaring it as let, as you cannot reassign a const):
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')
console.log(allfruits)
let fruits = ['banana', 'pear', 'apple']
fruits = fruits.concat('mango')
Append multiple items
To append a multiple item to an array, you can use push() by calling it with multiple arguments:
const fruits = ['banana', 'pear', 'apple']
fruits.push('mango', 'melon', 'avocado')
console.log(fruits)
You can also use the concat() method you saw before, passing a list of items separated by a comma:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango', 'melon', 'avocado')
console.log(allfruits)
or an array:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat(['mango', 'melon', 'avocado'])
console.log(allfruits)
Remember that as described previously this method does not mutate the original array, but it returns a new array.
Originally posted at
If you want to combine two arrays without the duplicate you may try the code below:
array_merge = function (arr1, arr2) {
return arr1.concat(arr2.filter(function(item){
return arr1.indexOf(item) < 0;
}))
}
Usage:
array1 = ['1', '2', '3']
array2 = ['2', '3', '4', '5']
combined_array = array_merge(array1, array2)
Output:
[1,2,3,4,5]
You .push() that value in.
Example: array.push(value);
If you want to append a single value into an array, simply use the push method. It will add a new element at the end of the array.
But if you intend to add multiple elements then store the elements in a new array and concat the second array with the first array...either way you wish.
arr=['a','b','c'];
arr.push('d');
//now print the array in console.log and it will contain 'a','b','c','d' as elements.
console.log(array);
We don't have an append function for Array in JavaScript, but we have push and unshift. Imagine you have the array below:
var arr = [1, 2, 3, 4, 5];
And we like to append a value to this array. We can do arr.push(6), and it will add 6 to the end of the array:
arr.push(6); // Returns [1, 2, 3, 4, 5, 6];
Also we can use unshift, look at how we can apply this:
arr.unshift(0); // Returns [0, 1, 2, 3, 4, 5];
They are main functions to add or append new values to the arrays.
You can use the push() if you want to add values,
e.g. arr.push("Test1", "Test2");.
If you have array you can use concat(), e.g. Array1.concat(Array2).
If you have just one element to add, you can also try the length method, e.g. array[aray.length] = 'test';.
Appending items on an array
let fruits = ["orange", "banana", "apple", "lemon"]; /* Array declaration */
fruits.push("avacado"); /* Adding an element to the array */
/* Displaying elements of the array */
for(var i=0; i < fruits.length; i++){
console.log(fruits[i]);
}
You can use the push method.
Array.prototype.append = function(destArray){
destArray = destArray || [];
this.push.call(this, ...destArray);
return this;
}
var arr = [1,2,5,67];
var arr1 = [7,4,7,8];
console.log(arr.append(arr1)); // [7, 4, 7, 8, 1, 4, 5, 67, 7]
console.log(arr.append("Hola")) // [1, 2, 5, 67, 7, 4, 7, 8, "H", "o", "l", "a"]
push() adds a new element to the end of an array.
pop() removes an element from the end of an array.
To append an object (such as a string or number) to an array, use:
array.push(toAppend);

Swap entire arrays in Javascript

When I try to make a function to swap 2 arrays, the original arrays are left unaltered.
function swap(x, y) {
var temp = x; x = y; y = temp;
}
u=[1, 0];
v=[0, 1];
swap(u, v);
console.log(u);
console.log(v);
This results in u as [1, 0] and v as [0, 1]. The values haven't been changed after the function call to swap.
On the other hand, if I do this without a function call:
u=[1, 0];
v=[0, 1];
var temp = u;
u = v;
v = temp;
console.log(u);
console.log(v);
Then they're swapped correctly, with u as [0, 1] and v as [1, 0].
I thought Javascript arrays are passed by reference, not by value. Am I misunderstanding something here?
Javascript does not have the ability to pass a reference to the u and v variables themselves. So, no assignment to x or y in your swap() function will change what is assigned to u or v. Javascript passes a reference to the object that u and v hold. Thus, you can't change the u and v variables from within swap(). You can change the contents of the object that they point to and thus properties of the object that u and v point to can be modified.
Since I have a C/C++ background, I think of what Javascript does when passing objects as "pass by pointer". When you call swap(u, v), what is passed to the swap() function is a pointer to the array that u also points to. So, now you have two variables u and x both "pointing" at the same array. Thus, if you modify that actual array, then since u points at that same array, both will see the modification. But, nothing you do inside the swap() function can change what object u or v actually point to.
In Javascript, the only way to change what object the original variables point to is to make them properties of an object and pass the object like this:
function swap(obj, x, y) {
var temp = obj[x]; obj[x] = obj[y]; obj[y] = temp;
}
var container = {};
container.u = [1, 0];
container.v = [0, 1];
swap(container, "u", "v");
console.log(container.u);
console.log(container.v);
If you don't mind rewriting both arrays from scratch, you can copy all the contents of one array to a temporary, then copy one array over to the other and then copy the temporary array contents back to the first original. This is not very efficient and there is probably a better way to solve your original problem, but it can be done.
function swap(x, y) {
// remove all elements from x into a temporary array
var temp = x.splice(0, x.length);
// then copy y into x
x.push.apply(x, y);
// clear y, then copy temp into it
y.length = 0;
y.push.apply(y, temp);
}
Getting the terminology on these "reference/value" questions is tricky, but I will do my best.
What you have for your Object / Array variables are really just references. Unlike C++, saying "x = y" does not actually copy the object's variables over to a new memory location. Internally, it's just copying a pointer location over. The language does not have constructions to "automatically recreate" something like an object or array in a new instance; if for some reason, you want to maintain two copies of an array, you will need to explicitly create it then copy over values (ie, = []; or = new Array(); or a copying function like = oldArray.map(...))
A little code example that might conceptually help. These same rules apply between objects and arrays.
a = {}; // In case you haven't seen it, this is like shorthand of "new Object();"
b = {};
c = b;
console.log(a === b); // false
console.log(b === c); // true
b.property = "hello";
console.log(c.property) // hello
Just like Java, JavaScript is pass-by-value only. Assigning to local variables in a function never has any effect on anything outside the function.
They are passed by reference, but they are also assigned by reference. When you write x = y you aren't modifying either of the arrays, you're just making your local variable x refer to the same array as y.
If you want to swap the array contents, you have to modify the arrays themselves:
function swap(x,y) {
var temp = x.slice(0);
x.length = 0;
[].push.apply( x, y );
y.length = 0;
[].push.apply( y, temp );
}
Feb 2022 Solution to Swap 2 Entire Array Contents.
You can use destructuring to swap the 2 arrays:
let a = [ 1, 2, 3, 4 ];
let b = ['a','b','c','d'];
[a,b] = [b,a]; // swap
console.log(a); // ["a", "b", "c", "d"]
console.log(b); // [1, 2, 3, 4, 5]
let a = [ 1, 2, 3, 4 ];
let b = ['a','b','c','d'];
[a,b] = [b,a]; // swap
console.log(a); // ["a", "b", "c", "d"]
console.log(b); // [1, 2, 3, 4, 5]
To swap 2 arrays you may use
Version 1
let arrA = [1,2,3,4];
let arrB = ['Eve', 'Bar', 'Foo'];
let tempArr = [arrA, arrB]; // constructing new array
arrA = tempArr [1];
arrB = tempArr [0];
Version 1 (shorthanded)
let arrA = [1,2,3,4];
let arrB = ['Eve', 'Bar', 'Foo'];
// RHS : construction a new array
// LHS : destruction of array
[arrB, arrA ] = [arrA, arrB];
Version 2 (spread operator)
let arrA = [1,2,3,4];
let arrB = ['Eve', 'Bar', 'Foo'];
let arrC = [...arrB]
arrB = [...arrA]
arrA = [...arrC]

Push data into JavaScript object

I have the following JavaScript object -
var newArray = { "set1": [], "set2": [] };
I am trying to push new data in this like -
newArray.set1.push(newSet1);
newArray.set2.push(newSet2);
Where newSet1 and newSet2 is equal to -
[{"test1","test1"},{"test2","test2"}] & [{"test3","test3"},{"test4","test4"}]
However when this is getting pushed in it is creating additional square brackets with the end result looking like -
{ "set1": [[{"test1","test1"},{"test2","test2"}]], "set2": [[{"test3","test3"},{"test4","test4"}]] }
When I actually need -
{ "set1": [{"test1","test1"},{"test2","test2"}], "set2": [{"test3","test3"},{"test4","test4"}] }
I tried setting my newArray as blank like -
var newArray = { "set1": '', "set2": '' };
However this did not work. How can I adjust it to accept the sets without adding additional brackets?
Use .concat()
var newArray = { "set1": [], "set2": [] };
newArray.set1 = newArray.set1.concat(newSet1);
newArray.set2 = newArray.set2.concat(newSet2);
You should say
newArray.set1.push(newSet1[0]);
newArray.set1.push(newSet1[1]);
newArray.set2.push(newSet2[0]);
newArray.set2.push(newSet2[1]);
newArray.set1 = newSet1;
newArray.set2 = newSet2;
Use Like
var newArray = { "set1": [], "set2": [] };
var arr1 = new Array ("A", "B", "C");
var arr2 = new Array (1, 2, 3);
var multiArr = new Array (arr1, arr2);
// or
var multiArr = [arr1, arr2];
// or
var multiArr = [["A", "B", "C"], [1, 2, 3]];
// you can access the elements of the array by zero-based indices
var firstRow = multiArr[0]; // same as arr1
var secondRowFirstCell = multiArr[1][0]; // 1
newArray.set1.push(multiArr[0]); //so, you need to use this with
newArray.set1.push(multiArr[1]); //so, you need to use this with
console.log(newArray);
DEMO

split an array into two based on a index in javascript

I have an array with a list of objects. I want to split this array at one particular index, say 4 (this in real is a variable). I want to store the second part of the split array into another array. Might be simple, but I am unable to think of a nice way to do this.
Use slice, as such:
var ar = [1,2,3,4,5,6];
var p1 = ar.slice(0,4);
var p2 = ar.slice(4);
You can use Array#splice to chop all elements after a specified index off the end of the array and return them:
x = ["a", "b", "c", "d", "e", "f", "g"];
y = x.splice(3);
console.log(x); // ["a", "b", "c"]
console.log(y); // ["d", "e", "f", "g"]
use slice:
var bigOne = [0,1,2,3,4,5,6];
var splittedOne = bigOne.slice(3 /*your Index*/);
I would recommend to use slice() like below
ar.slice(startIndex,length);
or
ar.slice(startIndex);
var ar = ["a","b","c","d","e","f","g"];
var p1 = ar.slice(0,3);
var p2 = ar.slice(3);
console.log(p1);
console.log(p2);
const splitAt = (i, arr) => {
const clonedArray = [...arr];
return [clonedArray.splice(0, i), clonedArray];
}
const [left, right] = splitAt(1, [1,2,3,4])
console.log(left) // [1]
console.log(right) // [2,3,4]
const [left1, right1] = splitAt(-1, [1,2,3,4])
console.log(left1) // []
console.log(right1) // [1,2,3,4]
const [left2, right2] = splitAt(5, [1,2,3,4])
console.log(left1) // [1,2,3,4]
console.log(right1) // []
Some benefits compared to other solutions:
You can get the result with a one liner
When split index is underflow or overflow, the result is still correct. slice will not behave correctly.
It does not mutate the original array. Some splice based solutions did.
There is only 1 splice operation, rather than 2 slice operations. But you need to benchmark to see if there is actual performance difference.
You can also use underscore/lodash wrapper:
var ar = [1,2,3,4,5,6];
var p1 = _.first(ar, 4);
var p2 = _.rest(ar, 4);
Simple one function from lodash:
const mainArr = [1,2,3,4,5,6,7]
const [arr1, arr2] = _.chunk(mainArr, _.round(mainArr.length / 2));
const splitArrayByIndex = (arr, index) => {
if (index > 0 && index < arr.length) {
return [arr.slice(0, index), arr.slice(-1 * (arr.length - index))]
}
}
const input = ['a', 'x', 'c', 'r']
const output = splitArrayByIndex(input, 2)
console.log({ input, output })

Categories

Resources