This question already has answers here:
Closed 10 years ago.
This question is an exact duplicate of:
How to append an array to an existing JavaScript Array?
How do you append an array to another array in JavaScript?
Other ways that a person might word this question:
Add an array to another
Concat / Concatenate arrays
Extend an array with another array
Put the contents of one array into another array
I spent some time looking for the answer to this question. Sometimes the simplest ones like these are the hardest to find answers to, so I am adding the question here hopefully with plenty of key words and phrases as per this blog post. Please feel free to answer this question with any other helpful information or edit the key words and phrases below.
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);
Related
This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 2 years ago.
i know how to create a one dimensional empty array like this:
var data = [];
var length = 100;
console.log(data);
for(var i = 0; i < length; i++) {
data.push(' ');
}
but how do i make the same thing, but two dimensional?
Your data is not an empty array, it is an array of 100 blanks/spaces.
If that's what you mean, then:
var length=100;
var data=[];
for(var i=0; i<length; i++) {
var innerData=[];
for(var j=0; j<length; j++) {
innerData.push(' ');
};
data.push(innerData);
}
I guess what you need is an array of arrays in that case you just fill the outer array with the number of arrays you want, you could use the for loop
var data = [];
var length = 100;
for(var i = 0; i < length; i++) {
data.push([]);
}
console.log(data)
or use fill instead as it's simpler, but the difference is all the arrays created will have same reference as the first array
array=Array(10).fill([])
console.log(array)
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 4 years ago.
I am a very beginner with Javascript and I'm working on a question from my Mentor that I'm totally stuck on:
Create a function that accepts one parameter. This parameter will be an array of objects. Each object will have 1 property name. The function should return a new array that is populated with the name properties from the objects.
Example
namesFunction([{name: 'Tacos'},{name: 'Burritos'},{name: 'Enchiladas'}]);
//returns ['Tacos', 'Burritos', 'Enchiladas']
I do not know how to make a for loop that will iterate over any array put into the function parameters. I've only done ones that have defined arrays.
This is what I have:
function namesFunction(){
var arr = [];
for (i = 0; i < arr.length; i++){
console.log(arr[i].name);
}
}
namesFunction([{name: 'Tacos'},{name: 'Burritos'},{name: 'Enchiladas'}]);
Any help is appreciated! Thank you!
You're writing a function that takes an array:
function mapObjectsToNames(array) {}
And you want it to return a new array:
function mapObjectsToNames(array) {
var result = [];
return result;
}
You're going to have to iterate over each element in the array:
function mapObjectsToNames(array) {
var result = [];
for (var i = 0; i < array.length; i += 1) {
}
return result;
}
You already were logging the name property from each element:
function mapObjectsToNames(array) {
var result = [];
for (var i = 0; i < array.length; i += 1) {
console.log(array[i].name);
}
return result;
}
Now you'll want to add the name to the new list:
function mapObjectsToNames(array) {
var result = [];
for (var i = 0; i < array.length; i += 1) {
result.push(array[i].name);
}
return result;
}
I have a question that is hard to describe. It's a tale of two arrays.
I have one array holding 50 objects. Per object, I want to call its specific property "IDnumber".
The second array is one that has 5 variables containing all of the mentioned 50 objects's "IDnumber" property, with each variable having a set of 10 IDnumbers: var1 is the IDnumbers of the first 10 objects, var2 is is the IDnumbers of the second set, and so on until the 50th object's ID number.
This is where it gets hard.
If I want to add in a new object in the first array, so that there'll be 51 objects, then I want to update the second array with a 6th variable, that contains all the remaining objects' IDnumbers (in this case just the 1). I want array2's length to be dependent on array1's length.
var arr1 = [], obj = {"IDNumber": "1"};
//this is an example array, all objects have the same ID here, but not in my real array
for (var i = 0; i < 51; i++) {
arr1.push(obj);
}
var var1 = [arr1[0]["IDNumber"], arr1[1]["IDNumber"], arr1[2]["IDNumber"], arr1[3]["IDNumber"], arr1[4]["IDNumber"], arr1[5]["IDNumber"], arr1[6]["IDNumber"], arr1[7]["IDNumber"], arr1[8]["IDNumber"], arr1[9]["IDNumber"]];
//the other remaining possible variables.
var arr2 = [var1, ...]; //No clue as how to take that on
How do I do that? How do I create an array that updates itself with newer possible variables like that? Each variable must have a max of 10 objects' IDnumbers.
Suppose array1 contains your array of objects. The other one is array2 containing an array of arrays, each sub array has length 10 like you stated
You can split array1 into groups of 10 and put in array2 like this
function slice10(arraysOfObject) {
var array2 = [];
var leftOver = arraysOfObject.length % 10;
var groupsOfTen = (arraysOfObject.length - leftOver)/10;
for (var i = 0; i < groupsOfTen; i++) {
array2.push([]);
for (var j = i*10; j < i*10 + 10; j++)
array2[i].push(arraysOfObject[j]["IDNumber"]);
}
//now take care of the leftover
if (leftOver > 0) {
array2.push([]);
for (var i = groupsOfTen*10; i < arraysOfObject.length; i++)
array2[array2.length-1].push(arraysOfObject[i]["IDNumber"]);
}
return array2;
}
You could create a function to deal with adding an object to the two different data structures, and use that function also for adding the first 50 objects:
function addObject(arr1, arr2, obj) {
if (arr1.length % 10 == 0) arr2.push([]);
arr1.push(obj);
arr2[arr2.length-1].push(obj.IDNumber);
}
var arr1 = [], arr2 = [];
for (var i = 0; i < 51; i++) {
addObject(arr1, arr2, {"IDNumber": i + 1000}); // some dummy ID value
}
console.log(arr2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Counting occurences of Javascript array elements
I have an array in javascript and for example the array is:
array(1,1,1,1,5,5,7,7);
If can some one please help me to understand how to count similar values,
And how to join similar values,
Thank you all and have a nice day.
var array = [1,1,1,1,5,5,7,7];
var count = 0;
var tempArray = array.sort();
var i;
var prevValue = null;
var joined = [];
for (i = 0; i < array.length; i++) {
if (tempArray[i] != prevValue) {
count++;
prevValue = tempArray[i];
joined.push(prevValue);
}
}
document.write(joined);
If you're looking to uniquely identify array contents:
Array.prototype.unique =
function() {
var a = [];
var l = this.length;
for(var i=0; i<l; i++) {
for(var j=i+1; j<l; j++) {
// If this[i] is found later in the array
if (this[i] === this[j])
j = ++i;
}
a.push(this[i]);
}
return a;
};
var myArray = [1,1,1,1,5,5,7,7];
var uniquedMyArray = myArray.unique();
var valueCountsMyArray = [];
for (var i = 0; i < myArray.length; i++) {
if (valueCountsMyArray[myArray[i]])
valueCountsMyArray[myArray[i]]++;
else
valueCountsMyArray[myArray[i]] = 1;
}
I can suggest using underscore.js. The code you're looking for isn't hard to write, and would be a good learning experience. Once you've done that, underscore is fantastic convenience library that offers what you're looking for, and you don't have to maintain it. :)
The uniq function will give you a copy of your array without duplicates, and the size function will tell you how many values that contains (or just reference the .length property).
Here a solution to count how many time it contains a number.
var count = [];
for(var i=0; i<array.length; i++) {
count[array[i]]++;
}
Let's say i have a for loop and i want to initialize multiple arrays in that loop. Can it be achieved like this?:
for (var i = 0; i < 5; i++){
var array+i = [];
}
So that the arrays that will be created are array0,array1,array2,array3,array4?
Any help would be much appreciated :)
You can use a multi dimensional array to tackle this problem:
for(var i=0;i<5;i++){
var array[i]=[];
}
which will result in:
array[0] = []
array[1] = []
array[2] = []
array[3] = []
array[4] = []
hope that helps :)
You can achieve something like that using
JavaScript Two Dimensional
Arrays
Building a MultiDimensional Array in
Javascript
JavaScript Multi-Dimensional
Arrays
JavaScript: Multi-dimensional
Array
You can create an array of arrays:
var arr = [];
for (var i = 0; i < 5; i++) {
arr[i] = [];
}
Or if it must be a global variable (probably not a good idea):
for (var i = 0; i < 5; i++) {
window["array" + i] = [];
}
You could probably eval it out,
for (var i=0;i<5;i++) {
eval("var array"+i+"=[];");
}
But eval is evil, it would make much more sense to just use a 2 dimensional array.
You can just use a two dimensional array.
Example to initialize 10 empty arrays:
let subArrays = Array.from({length: 10}, () => []);
If you're in a browser and willing to do something hacky you can use the top-level object, namely window:
for (var i = 0; i < 5; i++) {
window["array" + i] = [];
}
After doing this, you'll be able to refer to each array as array1 or whichever number you want.
This said, you should probably never actually use this method.