Multiple arrays in loop structure - javascript

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).

Related

How to compare all elements from two different arrays, programmatically

how can i make it so that my first loop loops through my first array and then another loop loops through the second array and compares the each of the element of the first array to all of the elements of the second array.
ex.
//first loop looping through my array1
for (var i = 0; i < array1.length; i++) {
//to store the element in
var test = array1[i]
//second loop looping through my array 2
for (var j = 0; j < array2.length; i++) {
//compares the current element in the array 1 to all the elements in array 2
if (test == array2[j]) {
alert(array2[j])
}
}
}
so basically i want it so that while the first loop is in the first element example array1[0] the next loop should compare array1[0] to all the elements present in the array2 and after its done that the next element array1[1] should be next to compare.
but when i run this it just alerts the first element of array 1 infinitely
If you want to find the common elements of each array and alert it, here's the solution.
const arrayOne = [16, 26, 41];
const arrayTwo = [10, 12, 26];
for (const element of arrayOne) {
if (arrayTwo.includes(element)) {
alert(element);
}
}
You have only one mistake. I can't comment because I don't have a reputation 50.
In your second loop put j++ instead of i++
you don't need test variable to compare
for (var i = 0; i < array1.length; i++) {
for (var j = 0; j < array2.length; j++) {
if (array1[i]== array2[j]) {
alert(array2[j])
}
}
}
And next time please ask questions clearly.

How to loop through all possible pairs of JSON object keys exactly once?

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

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);

Adding to array in for loop doesn't store value properly?

OK.. I really must be crazy. Why would these not print out 3-5 for "a"? I've tried two different methodologies to have the array store 3-5 below, and both of them seem.. obvious. There must be something in the underlying translation that I'm just not seeing.
<script>
var articlesKey = [];
for(var i = 3; i < 6; i++) {
articlesKey.push(i);
document.write('<br>i:'+i);
}
for (a in articlesKey)
document.write("<br>a:"+a);
articlesKey = [];
var count = 0;
for(var i = 3; i < 6; i++) {
articlesKey[count] = i;
document.write('<br>i:'+i);
count++;
}
for (a in articlesKey)
document.write("<br>a:"+a);
</script>
It prints out:
i:3
i:4
i:5
a:0
a:1
a:2
i:3
i:4
i:5
a:0
a:1
a:2
for( a in articlesKey) iterates a through the KEYS of articlesKey (letting you then get the values as articlesKey[a]). There is nothing wrong here.
That's very simply because a represents the array index in the loop, not the value at the index. Fix:
document.write("<br>a:"+articlesKey[a]);

Javascript : How should I run one `for`, for two arrays?

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.

Categories

Resources