How to compare all elements from two different arrays, programmatically - javascript

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.

Related

2d array with function javascript

I've task to create function that will display names from 2d array (const users). Each name should be displayed in separate line in console. Here is the code I've prepared but not sure if it's correct?
const users = [["Jaydn Humphries", "Ayda Orozco"], ["Sanjeev Wilkinson", "Jorge Markham"]];
function print2DArray(array) {
for(let i = 0; i < array.length; i++){
for(let j = 0; j < array.length; j++) {
console.log(array[i][j]);
}
}return array;
}
print2DArray(users);
Your inner for loop should run on the inner array not on the outer array.
i.e. j should be looped up to array[i].length not array.length
Although since in your example the inner arrays have the same length as the outer array, your example should work just fine.

How to compare a 1D array with a 2D array in JavaScript?

I have a 2D array and two 1D arrays. I have to compare the 1D array with the 2D array in JavaScript. I have written the following code but it is not working. Any help would be appreciated.
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [
['Cat', 'Brown', 2],
['Parrot', 'Brown', 1]
];
var col = [0,1];
var key = ['Parrot','Brown'];
for (var i = 0; i < arr.length; i++){
for (var j = 0; j < col.length; j++){
var isMatched = arr[i][col[j]] == key[j];
if (isMatched){
// write arr index
document.write(i);
// it should write 1 but writing 001
}
}
}
</script>
</body>
</html>
I am using 'col' array to store index of columns to be compared like in this case 0 for first column with values cat, parrot and so on. What I need is if all elements of 'key' array matches with any array of 'arr' then it should print true and index of matching array in 'arr'
Based on what you've mentioned in the comments, if you just want to check whether all the values in key array are contained in the other list of arrays arr. Then you don't necessarily need a col array and the following script should work.
var arr = [
["Cat", "Brown", 2],
["Parrot", "Brown", 1],
];
var key = ["Parrot", "Brown"];
for (let i = 0; i < arr.length; i++) {
// Current array from array of arrays, which you want to search
let array_to_be_searched = arr[i];
// Let's initially assume that all the elements of the key are included in this one
let isMatched = true;
for (let j = 0; j < key.length; j++) {
if (!array_to_be_searched.includes(key[j])) {
isMatched = false;
break;
}
}
// If our assumption is correct
if (isMatched) {
document.write(true); // Write true :)
document.write(i); // Index of current array
}
}
The output you are getting is "011" and not "001" are the index of "parrot" in key and then two time the index of "brown" in key.
After reading you comment I understood that you meant that "parrot" and "brown" should be found as a set in on of arr sub arrays.
So you have made the wrong comparisons - check this answerer to do the right one -
Check if an array contains any element of another array in JavaScript
and them make one loop to make the comparison.

Loop thought a multi dimensional array

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])
}

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

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