Creating a function, iterating through arrays, and pushing names - javascript

I am new to javascript and still trying to figure things out. I know little about basics and I ran into this problem and I'm not sure which line of code is wrong. Also, I'm trying to figure out how to console.log lines of code. Any help would be appreciated. Thank you!
Create a function named functions.imHere that creates and returns a new array. Within the function, iterate through the students array and use the .push() method to add each student to the new array.
here is my code:
functions.imHere = function() {
for(var i = 0; i < students.length; i++) {
newArray.push(students[i]);
return newArray;
}
};

Is this what you are looking for? Instantiate array before loop, insert elements inside the loop and return after the loop. Assuming that students is accessible within your function, otherwise you have pass students as an argument to your function.
functions.imHere = function() {
var newArray = [];
for(var i = 0; i < students.length; i++) {
newArray.push(students[i]);
}
return newArray;
};

Related

How do you push a specified number of objects to an array?

I'm pretty new to javascript but I'm trying to push a specified number of objects to an array using the following code. When I check the console I see only one object is pushed to the array. What should I be doing differently? Thanks!
var albums = {};
function collection(numberOfAlbums) {
array = [];
array.push(albums);
return array;
};
console.log(collection(12));
From your code:
array.push(albums);
would add the same object each time (assuming you had added a loop) which isn't what you want.
This will add a new empty object for each iteration of numberOfAlbums:
function collection(numberOfAlbums) {
for (var array = [], i = 0; i < numberOfAlbums; i++) {
array.push({});
}
return array;
};
Here's another way using map. Array.apply trick from here.
function collection(numberOfAlbums) {
var arr = Array.apply(null, Array(numberOfAlbums));
return arr.map(function (el) { return {}; });
};
I could give you the code but that is not learning. So here are the steps:
use numberOfAlbums as an argument in a function.
create an empty array.
use numberOfAlbums in for-loops in that for-loops push albums. ==array.push(albums)== do not use {}curly brackets around albums.
return the array.

How to work with multidimensional array when the number of dimension is variable?

Hello stackoverflow members.
I come with the following problem:
To start we have
var myArray = [[array1],[array2],[array3],[arrayN],...];
where each array is filled with a known number of strings such as
var array1 = ["a","b"], array2 = ["1","2"], array3=["&","é"];....
and so on.
I'm looking for a method to get this result:
expected result ===> a1&;a1é;a2&;a2é;b1&;b1é;b2&;b2é; ....
If the number of dimension were fixed I could use for loops to iterate and build the result, BUT here the problem is that I want to be able to enter N arrays in the main array myArray and by doing so, I change the depth of the nested loops.
If not do you have some ideas to put me on the track of the solution to this?
Thanks!
EDIT by the way this is what i experimented:
for (i=0; i<myArray[0].length; i++){
for (var j =0; j<myArray[1].length; i++){
for(var k = 0; k<myArray[2].length; k++{
console.log(i+j+k);
}
}
}
BTW i can't find a way to describe a function which would nest N for loops where N is myArray.length + 1 (the number of arrays in myArray).
EDIT: i found an iterative way of doing it and wanted to share the solution:JSFiddle
To get a flat list of all cells, something like the following recursive function should work (if you have a non-empty array of arrays, and all array items are strings):
function makeFlatList(inputArray) {
if (inputArray.length == 1) { // if this array has only one array inside
return inputArray[0]; // return the array inside
} else {
var outArr = [];
var arrayShifted = inputArray.slice(1); // remove first subarray from inputarray
var arrayShiftedFlat = makeFlatList(arrayShifted); // recursive call
for (var i=0; i<inputArray[0].length ; i++) { // loop over first array
for (var j=0; j<arrayShiftedFlat.length; j++) {
outArr.push(inputArray[0][i]+arrayShiftedFlat[j]); // add items to outArr
}
}
return outArr;
}
}
Working JSBin here

how to generate arrays automatically in javascript?

I want to make a loop that makes arrays automatically and assign the values to it.
The problem is how to generate the array itself automatically.
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray1 = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray1.push($("#"+idOfInput).val());
}
}
I want the loop to generate the array itself automatically like
catesArray1
catesArray2
catesArray3
and so on..
You need an object or an array to hold the multiple arrays you wish to create. Maybe something you are looking for is like the following?
var arrayHolder = new Array();
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray = new Array();
for(var attGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray.push($("#"+idOfInput).val());
}
arrayHolder.push(catesArray);
}
If you want the arrays to be in global namespace, You can try
window['catesArray' + attGetter] = [];
...
window['catesArray' + attGetter].push(...)
Else you can create a hash object and use it to hold the reference
var obj = {};
.....
obj['catesArray' + attGetter] = [];
.....
obj['catesArray' + attGetter].push(...)
In that case you will have to create one new array that holds all the cacatesArrays from first for loop
var catesArrayContainer = new Array(); //<<<---------------------
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray.push($("#"+idOfInput).val());
}
catesArrayContainer.push(catesArray); //<<<--------------------
}
EDIT :
This happens because the scope of variable catesArray1 was limited. When the loop enters next iteration the catesArray1 gets reinitialized, thus losing all the previously stored values...
Now in the code I have posted, we are storing every instance of catesArray1 in another array, and your values persist out side of the for loop
You can do something like this for 4 arrays of 5 elements each
yourarray=[];
for (i = 0; i <4; i++) {
temparray=[];
for (j = 0; j < 5; j++) {
temparray.push($('#'+whateverID+'_'+i+'_'+j)) //your values here
}
yourarray.push(temparray);
}
Check it on this JSFiddle. open chrome console to see array
If you want to create array within loop from index
You can use eval to evaluate javascript from strings but i wont use that unless there is no other way. you can see both above and eval method in this Fiddle. Open Chrome console to see array values
Just a comparison of using eval and 2D array
Open console in chrome while you run this jsFiddle and you will see the difference in eval and 2darray in context of this question.
You should assign them to an object. In this case, make an object variable before the first for-loop to hold all arrays:
var allArrays = {};
for(var attGetter=1; attGetter <= num; attGetter++){
var currentArray = allArrays['catesArray' + attGetter] = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
currentArray.push($("#"+idOfInput).val());
}
}
Instead of attempting to create & allocate dynamically named variables, I would think of this more of an array of array's if you will. In other words, create an array that holds all of the arrays you want:
var collections = []; // Literal notation for creating an array in JS
From here, it's a matter of making each value you create within this array its own array:
var n = 10; // Total amount of arrays you want
for (var i = 0; i < n; i++) {
var values = [];
// Have another loop that fills in the values array as expected
collections.push(values); // Each element at collections[i] is its own array.
}
If you truly need named elements, you could potentially do something very similar with just an object {} instead, and refer to each element by a name you create.
var collections = {}; // Literal notation for an object in JS
var n = 10; // Total amount of arrays you want
for (var i = 0; i < n; i++) {
var values = []; // Literal notation for an array in JS
// Fill in the values array as desired
var name = 'arr' + i; // How you'll refer to it in the object
collections[name] = values;
}
I suggest the former though, since it does not sound like you need to have explicit names on your arrays, but just want multiple layers of arrays.

accessing elements in a list in javascript html

I have a list - [getFamilyPkg, getActivePkg, getEligiblePkg, getActivePkgForDeactivation], want to get each element in this list in a javascript function.
How to do it? Thanks in advance.
Assume list is stored in a variable called arr.
for (var i = 0; i < arr.length; i++) {
var elem = arr[i];
// elem is either getFamilyPkg, or getActivePkg, or ...
}
Tommy's answer is actually incorrect. for (var i in arr) loops over all attributes/properties of the arr object prototype, which includes builtin functions like slice(), etc. See jsfiddle example here: http://jsfiddle.net/sEtMw/ (check the console and you will see a bunch of extra properties other than the array elements.
There are a few approaches (once again assuming the array is named arr):
var elem;
for (var i = 0, len = arr.length; i < len; i++) {
elem = arr[i];
// elem is actually one of the array elements here
}
Another option is as follows:
var elem;
while (elem = arr.shift()) {
// elem is one of the array elements
}
Please note that the second approach does not keep the array intact. i.e. at the end of the loop, the array will be empty. But if you are okay with that, the syntax is definitely cleaner. Both approaches are illustrated here: http://jsfiddle.net/z7zKK/. The variable arr is logged at the end to illustrate that it is empty.

.slice() method in Javascript not copy by value

Okay so I am trying to make an AI for a game called notakto. That much isn't relevant however, in order to make the search algorithm that I do I need to duplicate array. So I have a global array called board which looks like this [[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]] where all of the 0s are different numbers.
To copy this I have the following line. var newboard=board.slice(). Problem is when I run a line of code like newboard[0][0]=1 it changes also acts as if I have run the following board[0][0]=1.
You copy your array, but the inner arrays are not copied. This is a litte bit hacky but it works:
var newboard = JSON.parse(JSON.stringify(board));
In this context it will work, but if your object has any functions these are lost through stringify. Moreover it could make some trouble with Data objects which are stored inside the object.
javascript is always reference based. if you want to make a duplicate copy, please do deep object copy instead of sallow copy.
In angular, angular.copy() will perform deep copy.
var newboard=angular.copy(board.slice());
It's because nested arrays are shallow-copied by reference. You can use a recursive function like this to deep-copy a multidimensional array such as the one you have above, making sure that each nested array is copied by value:
function copyMultidimensionalArray(array) {
var r = array.slice(0);
for (var i = 0, l = r.length; i < l; ++i) {
if (Array.isArray(r[i])) {
r[i] = copyMultidimensionalArray(r[i]);
}
}
return r;
}
/* example */
var board = [[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]],
anotherBoard = copyMultidimensionalArray(board);
anotherBoard[0][0] = 99;
document.write([
"board[0][0] ===",
board[0][0],
"&& anotherBoard[0][0] ===",
anotherBoard[0][0]
].join(" "));
You can also use board.map(function(cv){ return cv.slice();}) to copy the board:
var board = [[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]];
var board2 = board.map(function(cv){ return cv.slice();});
board2[0][0] = 1;
console.log(board);
console.log(board2);

Categories

Resources