How to compare a 1D array with a 2D array in JavaScript? - 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.

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

Why I'm getting undefined when I tried to access the element from nested array in javascript?

I am trying to access the elements from multidimensional array in javascript. When I tried to access the element from the arrays inside the array with a variable I'm getting undefined as a result. I'm getting the result if I used number instead of variable..
let arr = [[1,2,3],[4,5,6],[7,8,9]];
for(let i=0; i < arr.length; i++) {
console.log(arr[i][arr.length]);
}
Because the length of the array is 3, and your last array index is 2. You could modify it:
let arr = [[1,2,3],[4,5,6],[7,8,9]];
for(let i=0;i<arr.length;i++){
console.log(arr[i][arr.length - 1]); // Note the -1
}
This will return 3, 6, 9
If you want to access all the elements in the nested arrays you will need two for loops, one to iterate the first level and the other loop to interate the inner level.
let arr = [[1,2,3],[4,5,6],[7,8,9]];
for(let i=0; i < arr.length; i++) {
//looping through the outer array
console.log(arr[i])
for(let j=0;j< arr[i].length;j++)
{
//looping through the inner arrays
console.log(arr[i][j]);
}
}

How get combination of sums of numbers in Array

I have an array and i want to get all combination of sums of its number.
let arr=[1,2,3,4,5];
1st iteration : 1+2=3,1+3=4, 1+4=5, 1+5=6
and array becomes arr[1,2,3,4,5,6]
2nd iteration : 2+1=3,2+3=5, 2+4=6, 2+5=7
and array becomes arr[1,2,3,4,5,6,7]......
and 1+2+3=6, 1+2+4=7
.
.
.
and 1+2+3+4=10
.
.
.
and 1+2+3+4+5=15
and final array becomes =[1,2,3,4,5,6,7,8,9,10,11,15]
Can anyone help me to build an algo for this?
Here is what i have tried so far, I tried to prepare array of possible sub arrays of arr but could not get all combination.
let arr=[1,2,3,4,5];
let a=[];
for(let i=0; i < arr.length; i++){
for(let j=0; j < arr.length; j++){
let b=[];
for( let k=i; k<=j; k++ ){
b.push(arr[k]);
}
a.push(b);
}
}
console.log(a);
You can use a dictionary or associative array (which JavaScript's arrays are) to store which sums can be made, by using the sum as the index and setting the element to 'true', similar to creating a sieve; you can then iterate over this sparse array efficiently with for in.
function sums(values) {
var dictionary = [];
for (var i in values) {
var temp = [values[i]]; // start with value by itself
for (var j in dictionary) {
temp.push(values[i] + Number(j)); // sum of value and values already in dictionary
}
for (var k in temp) {
dictionary[temp[k]] = true; // transfer values to dictionary
}
}
var output = [];
for (var i in dictionary) {
output.push(Number(i)); // convert dictionary to array of values
}
return output;
}
document.write(sums([2,5,11,16]));

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

Categories

Resources