Looping array inside and array - javascript

I'm want to loop an array inside and array using JavaScript
outerArray = ["1","2","3","4","5","6","7","8","9","10"];
innerArray = ["val-1","val-2","val-3"];
so that the console logs out:
1,val-1
2,val-2
3,val-3
4,val-1
5,val-2
6,val-3
7,val-1
8,val-2
9,val-3
10,val-1
Using:
for (var i = 0; i < outerArray.length; i++) {
console.log(i);
}
Obviously logs:
1,2,3,4,5,.....
However I cant use:
for (var i = 0; i < outerArray.length; i++) {
console.log(i+','+innerArray[i]);
}
As this would give undefined after "val-3" as its a different length to the outer array.

You seem to want
console.log(outerArray[i]+','+innerArray[i%innerArray.length]);
Reference on the % operator

outerArray.forEach(function (elem, idx) {
console.log(elem + ", " + innerArray[idx % innerArray.length]);
});
http://jsfiddle.net/bh4bs/

Related

How to create multiple arrays of random numbers in js?

I am attempting to create a matrix of 3 arrays with 10 elements in each array. Each element should be a random number between 1 and 10. I wanted to use a single function to generate each of the arrays, and used this:
var array1 = [];
var array2 = [];
var array3 = [];
var tempName;
function fcnArrayGenerate(){
let i = 1;
while (i < 4){
tempName = "array" + i;
let j = 0;
while (j < 10){
tempName.push((Math.floor(Math.random() * 10) + 1));
j++;
}
i++;
}
console.log(array1);
console.log(array2);
console.log(array3);
}
However, when I run the function, I receive an error stating that "tempName.push is not a function." Any assistance on how to correct this would be appreciated. Thank you.
Instead of using three variables for three different arrays, you can use a single multidimensional array to store those three arrays.
let array = [[], [], []];
function fcnArrayGenerate() {
let i = 0;
while (i <= 2) {
let j = 0;
while (j < 10) {
array[i].push(Math.floor(Math.random() * 10) + 1);
j++;
}
i++;
}
}
// call the function
fcnArrayGenerate();
// now print the arrays as tables
console.table(array);
console.table(array[0]);
console.table(array[1]);
console.table(array[2]);
Note: console.table() allows you to print out arrays and objects to the console in tabular form.
If you want to push into tempName you have to initialise it with an empty array first. Right now it’s undefined. Hence you’re seeing the error as you can’t push something to undefined
Do this:
var tempName = []
To make variable names incremental, you can pass them as objects.
var data = {
array1: [],
array2: [],
array3: []
}
function fcnArrayGenerate(){
let i = 1;
while (i < 4){
let j = 0;
while (j < 10){
data['array' + i].push((Math.floor(Math.random() * 10) + 1));
j++;
}
i++;
}
console.log(data.array1);
console.log(data.array2);
console.log(data.array3);
}
fcnArrayGenerate();

How to create javascript array when each element is a pair of objects

hello I would like to build an array that every element will be a pair of objects , Something like this
var Shelves = new arr[][]
var books = new Books[] ;
Shelves[book[i],book[j=i+1]],[book[i+1],book[j=i+1]] and so on......;
I mean that I understand how to go with a for loop and to get the elements 'but how to push them in pairs array? arr.push doesn't work :(
build1ArrPairs(1Arr) {
if (1Arr != undefined || 1Arr!=null) {
for (var i = 0; i < 1Arr.length; i = i + 1) {
for (var j = i + 1; j <= 1Arr.length; j++) {
this.1ArrPair.push(1Arr[i] 1Arr[j]);
break;
}
}
}
}
Thanks :)
Alternatively, you can use array#reduce to group your array.
var names = ['a', 'b','c','d','e'];
var result = names.reduce((r,w,i) => {
let index = Math.floor(i/2);
if(!Array.isArray(r[index]))
r[index] = [];
r[index].push(w);
return r;
},[]);
console.log(result);
First of all, variables names can't start with a number.
Second, initialize an array, then add your elements - two at a time - and return the array:
var ans = [];
if (Arr != undefined || Arr != null) {
for (var i=0; i<(Arr.length-1); i+=2) { // Note the loop stops 2 elements before the last one
ans.push([Arr[i], Arr[i+1]]);
// ^ Note the comma - it's missing in your code
}
}
return ans;

For loop withoit indexes javascript

I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration.
I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.
var a = [];
for (var i = 1; i < 8; i++) {
a[i] = i;
};
console.log(a);
Outputs:
[1: 1, 2: 2 ...]
Desired output:
[1,2,3]// same as console.log([1,2,3])
Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.
You need to push values to array:
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
I have to disagree with the answers provided here. The best way to do something like this is:
var a = new Array(7);
for (var i = 0; i < a.length; i++) {
a[i] = i + 1;
}
console.log(a);
Your code is making each index equal to i, so use it this way
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);

loop on Multiple array values

I am confused about how to iterate on multiple values.
for example : values.categories[0].num[0].entry[0].label;
Do I need to write three for loops in order to iterate through categories, num and entry.
Because categories[0] will always identify the 1st position, but am looking for generic categories[i].
Can you please help me out whether to write three for loops or better option is there to achieve.?
This is what I have tried:
var result = [];
for (var i = 0; i < categories.length; i++) {
var abc = categories[i].num;
for (var j = 0; j < abc.length; j++){
var def = num[i].entry;
}
for(var k = 0; k < def.length; k++){
var ghi = entry[i].label;
result.push(ghi)
console.log(result);
}
}
you can use the each function of jquery.
$.each(categories, function(ci, num) {
// This set the index of the array in ci and the value in num = categories[ci]
$.each(num, function(ni, entry) {
// etc ...
});
});
if you want it to stop the iteration you can return false inside the callback function.

Display random array properties in for loop

I have for loop that alerts strings from array, I wonder how can I alert them randomly, so it will run gamesNames.length times and display them in different-random order each time (without duplicating them) in JavaScript ?
for (var i = 0; i < gamesNames.length; i++) {
alert (gamesNames[i].Name + gamesNames[i].year );
}
here is a Link http://www.javascriptkit.com/javatutors/arraysort.shtml to the main idea, in Javascript
and here is the Code
...
gamesNames.sort(function() {return 0.5 - Math.random()}) ;
for (var i = 0; i < gamesNames.length; i++) {
alert (gamesNames[i].Name + gamesNames[i].year );
}
...
I hope this helps.
Create an array with items that contain an index and a random number. Shuffle them by sorting on the random number, and use the index to alert the items:
var idx = [];
for (var i = 0; i < gamesNames.length; i++) {
idx.push({ idx: i, rnd: Math.floor(Math.random() * 100000) });
}
idx.sort(function(x,y){ return x.rnd - y.rnd; });
for (var i = 0; i < idx.length; i++) {
var j = idx[i].idx;
alert (gamesNames[j].Name + gamesNames[j].year);
}
You can use a while-loop for this easily, in combination with array.splice:
var array = ["1", "2", "3", "4"];
while(array.length > 0)
{
// Get a random index
var index = Math.floor(Math.random() * array.length);
// Append it to the DOM (or do whatever you want with it)
$("body").append($("<p />").html(array[index]));
// Remove it from the array
array.splice(index, 1);
}
JSFiddle

Categories

Resources