I have:
var array1 = [];
var array2 = [];
array1 contains 1,2
array2 contains 3,4
And I want to do this:
for(var a in array1){
for(var b in array2){
doSomething(array1[a],array2[b]);
}
}
But the problem is that function doSomething() runs twice for each array because of the two for's.
How should run it just once but with all of the arrays?
EDIT
The numbers are not in ascending order! In my real project they are ID's what can be any number in any order.
You shouldn't use for..in for looping through arrays. Use an index variable:
for (var i = 0, len = array1.length; i < len; i++) {
doSomething(array1[i], array2[i]);
}
This of course assumes they're the same length.
I think this is what you're after:
for(var i=0; i<array1.length; i++){
doSomething(array1[i],array2[i]);
}
This loops through both arrays, using the first for the length, and taking the element at the same index in both for each doSomething() call.
If you are sure that both arrays have the exact same length, you can do the following:
for (var i = 0; i < array1.length; i++) {
doSomething(array1[i], array2[i]);
}
It looks like you want to concatenate two arrays together. Use the concat() function:
var jointArray = array1.concat(array2);
for(var i=0; i < jointArray.length; i++) {
doSomething(jointArray[i]);
}
See:
http://www.w3schools.com/jsref/jsref_concat_array.asp
This if array arent same length
for (var i = 0, i < (array1.length <= array2.length ? array1.length : array2.length); i++) {
doSomething(array1[i], array2[i]);
}
DoSomething will run 4 times. If you want it to just run through the values both list together, remove the second for loop and replace b in DoSomething with a.
Related
I try to return a multidimensional array into a function to iterate it but I'm not sure what's wrong with my logic
const arr = [[1,2], [3,4],[5,6]]
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i], thirdInterval[i+1])
}
The result that I want to achieve is return the first element into the first argument of the function and the second element of the array into the second argument of the function.
What you are doing here is looping through the array and getting only the array at the index i, e.g arr[0] which is [1,2]. and (thirdInterval[i], thirdInterval[i+1]) is actually equals to ([1,2], [3,4])
to access the first and second elements you should address them like the following:
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i][0], thirdInterval[i][1])
}
const arr = [[1,2][3,4][5,6]];
for (var i = 0; i < arr.length; i++;) {
func(arr[i][0], arr[i][1];
}
You are iterating an array with sub-arrays, which means that thirdInterval[i] contains two items. You can get the items using the indexes thirdInterval[i][0] and thirdInterval[i][1], but since you're calling a function with those values, you can use spread instead - getNumbers(...thirdInterval[i]).
In addition, the loop's condition should be i < thirdInterval.length if you don't want to skip the last item.
Demo:
const thirdInterval = [[1,2],[3,4],[5,6]]
const getNumbers = console.log // mock getNumbers
for (let i = 0; i < thirdInterval.length; i++) {
getNumbers(...thirdInterval[i])
}
Say that I have a data structure of n elements and a function check(element1, element2) which performs some kind of checkup on two elements. I need to check exactly all possible pairs of elements. Using combinatorics it is easy to deduce that we need to perform exactly 'n choose 2' binomial coefficient iterations ( n*(n-1)/2 iterations)
So if my data structure is an array, the following nested loops would work:
for(let i = 0; i < elements.length; i++) {
for(let j = i + 1; j < elements.length; j++) {
check(elements[i], elements[j]);
}
}
This way we check the first element with all the others, the second element with elements 3 to n (since we already checked it with the first one), the third with elements 4 to n and so on and so forth. However if 'elements' was a JSON where the key to each element is not an integer, how can we achieve this effect? Obviously we can ensure that we perform all checkups with the following code:
for(var key1 in elements) {
for(var key2 in elements) {
if(key1 != key2) {
check(elements[key1], elements[key2]);
}
}
}
However obviously we are doing a lot of checkups more than once resulting in n^2 iterations.
What method can I use to achieve the same result as in the example with the array?
If you put all the keys you're going to be looping into an array using Object.keys() then you can use your standard for loop to "skip" over previously seen keys like so:
const keys = Object.keys(elements);
for(let i = 0; i < keys.length; i++) {
const key1 = keys[i];
for(let j = i + 1; j < keys.length; j++) {
const key2 = keys[j];
check(elements[key1], elements[key2]);
}
}
Perhaps you could get the list of keys in an array:
let elements = { a: 1, b: 2, c: 3 };
let keys = Object.keys(elements).sort(); // Sorts the keys array alphabetically, and thus simulating the numbers example and be sure you're not repeating "lower" order key after passing it
for(let i = 0; i < keys.length; i++) {
for(let j = i + 1; j < keys.length; j++) {
// check(elements[keys[i]], elements[keys[j]]);
console.log(elements[keys[i]], elements[keys[j]])
}
}
output:
1 2
1 3
2 3
Wondering why i needed to add 4 to the array length in order for it to print out the entire array in reverse?
before i added 4 it was just using the .length property and it was only printing out 6543.
thanks in advance!
function reverseArray(array) {
var newArray =[];
for(var i = 0; i <= array.length+4; i++) {
newArray += array.pop(i);
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));
array.pop removes (and returns) the last element. This affects the length of the array. The length is checked on every iteration, so since the array is getting shorter every time, the loop is ended early.
You can create a loop and pop items until it is empty, but another thing to take into account, is that it is the original array you are altering. I think a function like reverseArray shouldn't alter the array numbers that was passed to it if it returns another one. So a better solution would be a simple loop that iterates over all items without modifying the array.
function reverseArray(array)
{
var newArray =[];
for (var i = array.length-1; i >= 0; i--) {
newArray.push(array[i]);
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));
console.log(numbers); // Should be unaltered.
If you don't mind modifying the array, you can use the reverse() method of the array:
var numbers = [1,2,3,4,5,6];
numbers.reverse();
console.log(numbers);
In Javascript, pop always removes the last element of the array. This shortens length, meaning that i and array.length were converging.
You can do a few things to avoid this behavior:
Store the original length when you start the loop: for (var i = 0 , l = array.length; i < l; i++)
Copy over values without modifying the original array
When you pop the items from the array, the item is removed from the array. As you increase the counter and decrease the length, they will meet halfway, so you get only half of the items.
Use push to put the items in the result. If you use += it will produce a string instead of an array.
If you use pop, then you can just loop while there are any items left in the array:
function reverseArray(array) {
var newArray = [];
while (array.length > 0) {
newArray.push(array.pop());
}
return newArray;
}
You can leave the original array unchanged by looping through it backwards and add items to the new array:
function reverseArray(array) {
var newArray = [];
for (var i = array.length - 1; i >= 0; i--) {
newArray.push(array[i]);
}
return newArray;
}
use following method for same output
function reverseArray(array)
{
var newArray =[];
var j = array.length-1;
for(var i = 0; i < array.length; i++)
{
newArray[j]= array[i]; j--;
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));
I cannot think of a way to loop through two arrays at the same time. This code is for outputting a function's data to different divs on a page. array1 defines the input and array2 defines the output.
How can I loop through the two arrays so that item1 will always be paired with '#div1', item2 with '#div2', etc.
var array1=[item1 , item2, item3, item4];
var array2=['#div1', '#div2', '#div3', '#div4'];
for (var i = 0; i < array1.length; i++) {
//code for to populate data goes here
item.appendTo($(array2[i]));
};
Am I at least correct in wrapping my function in a for loop?
Thank you!
var array1=[item1 , item2, item3, item4];
var array2=['#div1', '#div2', '#div3', '#div4'];
for (var i = 0; i < array1.length; i++) {
//code for to populate data goes here
$(array1[i]).appendTo(array2[i]);
};
Using the $() creates a jQuery object. You probably want to be creating the jQuery object off of the array2 values. When using a for loop the i variable will increment and you can use this to access the array members. Since you want the same index of both arrays using this for loop should work well
var array1=[item1 , item2, item3, item4];
var array2=['#div1', '#div2', '#div3', '#div4'];
for (var i = 0; i < array1.length; i++) {
$(array2[i]).append(array1[i]);
};
You can just iterate over two arrays at once. For security, just check if your index variable ('i') is not exceeding any of both arrays length.
Here's an example:
var array1=[item1 , item2, item3, item4];
var array2=['#div1', '#div2', '#div3', '#div4'];
var array3 = [];
for ( var i = 0; i < array1.length && i < array2.length; i++ ) {
array3.push({
el1: array1[i],
el2: array2[i]
});
}
for ( var i = 0; i < array3.length; i++ ) {
// array3[i].el1; -- element from array1
// array3[i].el2; -- element from array2
}
You can do this in one loop, of course. Here I've gone with two just for clarity (second one is logging only).
I now multi-dimensional array in javascript is a bit silly. But in my program I have to use it.
I want to declare a dynamic 3 columns and m-rows array using javascript and then in a loop i need to insert some element to that array. finally i want to display that array.
var x = new Array();
for (var y=0; y<=counter; y++) {
x[y] = new Array (3);
x[y][0]='a';
x[y][1]='b';
x[y][2]='c';
}
your help is highly appreciated ...
arrays grow as needed and so there is no point in declaring the length of the array. what you started with is fine.
http://books.google.ca/books?id=4RChxt67lvwC&pg=PA141&lpg=PA141&dq=JS+array+grow+as+needed?&source=bl&ots=tgY8BlGXm8&sig=_3jcH1LTmYi9QiXxn9pHROpbN1s&hl=en&sa=X&ei=7v60T_XwA4ThggfGuoEX&ved=0CEoQ6AEwAQ#v=onepage&q=JS%20array%20grow%20as%20needed%3F&f=false
http://www.codingforums.com/showthread.php?t=5198
just a heads up it will create an array that is 1 bigger then counter. this is b/c in your for loop you have y<=counter and y starting at 0. if you want the length to be counter change it to
y<counter
in order to display the array you might want to consider a for nested loop.
JS
for(var i=0; i<x.length; i++)
for (var j=0; j<3; j++)
alert(x[i][j]);
where x is the reference to the array.
if you want to print the entire array at once consider creating a string from the elements in the array and print that
function displayArray(x){
var stringArray='';
for(var i=0; i<x.length; i++)
for (var j=0; j<3; j++)
stringArray+= x[i][j];
alert(stringArray);
}
Something like this?
var x = [
[
[1, 2, 3],
[4,5,6]
],
[
[7, 8, 9]
]
];
alert(x[0][1][2]);
This is one reason why JavaScript's variable syntax isn't always what it's cracked up to be. Compare to Java:
String[][][] x = new String[5][5][5];
Something like this maybe?
var sDataArray=MultiDimensionalArray(7,2);
alert(sDataArray[0][0]);
function MultiDimensionalArray(iRows,iCols)
{
var i;
var j;
var a = new Array(iRows);
for (i=0; i < iRows; i++)
{
a[i] = new Array(iCols);
for (j=0; j < iCols; j++)
{
a[i][j] = "";
}
}
return(a);
}
Being dynamic in rows maybe you want a list of arrays? You can also do a method to add a line, and increase the array size.
try something like this..
var cols = 3;
var rows = 5;
createArray(cols,rows);
function createArray(cols,rows) {
var newArray = [];
for(i=0;i<cols;i++) {
newArray[i] = [];
for(j=0;j<rows;j++) {
newArray[i][j] = "["+i+"]"+"["+j+"]";
}
}
return newArray;
}