How to extend an existing JavaScript array with another array, without creating a new array
The .push
method can take multiple arguments. You can use the spread operator to pass all the elements of the second array as arguments to .push
:
>>> a.push(...b)
If your browser does not support ECMAScript 6, you can use .apply
instead:
>>> a.push.apply(a, b)
Or perhaps, if you think it's clearer:
>>> Array.prototype.push.apply(a,b)
Please note that all these solutions will fail with a stack overflow error if array b
is too long (trouble starts at about 100,000 elements, depending on the browser).
If you cannot guarantee that b
is short enough, you should use a standard loop-based technique described in the other answer.
Append an array to another array in JavaScript
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
var array1 = ['a','b','c'];
var array2 = ['d','e','f'];
var array3 = ['g','h','i'];
array1.pushArrayMembers(array2, array3);
document.body.textContent = JSON.stringify(array1, null, 4);
Copy array items into another array
Use the concat function, like so:
var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);
The value of newArray
will be [1, 2, 3, 4]
(arrayA
and arrayB
remain unchanged; concat
creates and returns a new array for the result).
Replace nested array for new array
You can achieve that by using spread operator and without any loop as you want to replace second array with the new array.
Input array :
First Array
[{
Second Array
[{}]
}]
Logic to replace newArray
with secondArray
:
FirstArray[0].secondArray = [ ...newArray ]
Demo :
const firstArray = [{
secondArray: ['alpha', 'beta', 'gamma']
}];
const newArray = ['A', 'B'];
firstArray[0].secondArray = [ ...newArray ];
console.log(firstArray);
Add elements of an array to another array
You can use ES6 syntax for make this :
You can make something like that :
const arr1 = ["a", "b"];
const arr2 = ["c", "d"];
arr1 = [...arr1,...arr2]
console.log(arr1)
push the contents of array into another array without looping
You can spread
the content of both arrays into the new array
const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);
// prints [1,2,3,4,5,6]
Spreading arr2
into arr1
also works.
arr1.push(...arr2);
console.log(arr1);
// prints [1,2,3,4,5,6]
So changing
ordersArr.push(tOrders)
to
ordersArr.push(...tOrders);
should work.
For a full answer:
let ordersArr = [];
let orders = {
foo: [
{x: 1, b: 2},
{y: 1, c: 3},
{a: 2, d: 4}
]
}
orders2 = {
foo: [
{x: 2, b: 3},
{y: 5, c: 4},
{a: 3, d: 6}
]
}
ordersArr.push(...orders.foo, ...orders2.foo);
Javascript: How to extend an array with a dictionary with { key: array values} without logging [Object] to console
arr.push(h) gives [ { toys: [ [Object] ] } ]
This is because console.log
somewhere does not show the deep levels of nested objects. You just need to use console.dir
with the depth
option. Check this out:
h = { toys: [{ name: 'Toy 1', price: 900 }] };
arr = [];
arr.push(h);
console.dir(arr, { depth: null });
Duplicate and computation of array to another array without Modification of Original array
I would suggest using Array.map to produce the desired result, once for each array in arr
, and again for each element in this array.
var arr = [
[1, 2],
[2, 3],
[3, 4]
];
function clicked() {
var scale = 1.1;
var newArray = arr.map(element => element.map(e => e *= scale));
console.log('New Array: ', newArray);
console.log('Old Array: ', arr);
}
document.querySelector('#click').addEventListener('click', function() {
clicked();
});
<button class="click" id="click"> Click me and check Console</button>
Related Topics
Jquery Event That Triggers After CSS Is Loaded
Copy to Clipboard Using JavaScript in iOS
Invoke Method in Objective C Code from HTML Code Using Uiwebview
Simplest Way to Detect a Pinch
How to Make Changeable Themes Using CSS and JavaScript
How to Dynamically Modify <Select> in Materialize CSS Framework
Generate Dynamic CSS Based on Variables Angular
Can Jquery Change CSS Style Definition? (Not Individual CSS of Each Element)
Preventing Child from Firing Parent's Click Event
How to Check If an External (Cross-Domain) CSS File Is Loaded Using JavaScript
Google Seo and Hidden Elements
Manipulating CSS with JavaScript
Refused to Load the Script Because It Violates the Following Content Security Policy Directive
Correct Try...Catch Syntax Using Async/Await
Programmatically Focus on Next Input Field in Mobile Safari
I'Ve Heard Global Variables Are Bad, What Alternative Solution Should I Use
Get Element's Custom CSS Properties (-Mystyle) Using JavaScript