Corresponding arrays (Javascript) - javascript

So let's say I have two arrays
var x = [1,2,3,4,5,6]
var y = [A,B,C,D,E,F]
I want to display the values of the variables together based on their index location/value. eg: so A corresponds with 1, B corresponds with 2, etc, like so:
A,1
B,2
C,3
etc
How can I display them together based on their index location?

Assuming they always match, just loop one and reference both:
for (var i = 0; i < x.length; i++) {
console.log(y[i] + "," + x[i]);
}

Related

Efficient way to create nested objects JavaScript

Are there any more efficient ways to create nested objects than nested for approach?
I am trying to hold 25 random numbers (1 - 71), 5 row x 5 column. I will iterate through each item to check if ballPicker() function (not yet implemented) has picked a number that the object has. So I need to keep the information that if a number was found. I could have done it with a 5 x 5 array but iterating that array will not be as efficient as objects.
I have an array starting from 1 to 71 (inclusive, step is 1).
I shuffle the array in createRandomNumberArray() function. So shuffledNumbers array values are not sequential
let shuffledNumbers = Array.from({length: 71}, (v, i) => i + 1);
function createRandomNumberArray() { //Fisher - Yates shuffle algorithm
let randomPosition;
let temp;
for (let i = shuffledNumbers.length - 1; i > 0; i--) {
randomPosition = Math.floor(Math.random() * (i + 1));
temp = shuffledNumbers[i];
shuffledNumbers[i] = shuffledNumbers[randomPosition];
shuffledNumbers[randomPosition] = temp;
}
}
In createBoards() function I am creating an object (board) that holds 5 objects (row) with their indexes as property name. And row has 5 objects (cell) with their indexes as property name again. Cell has only one object that gets its property name from slicedArray(slicedArray is a 5 item slice from shuffledNumbers that holds non duplicated random numbers (range inclusive 1 to inclusive 71)) and its value is always false.
function createBoards() {
let board = {};
for (let i = 0; i < 5; i++) {
let row = {};
let slicedArray = shuffledNumbers.slice((i * 5), ((i + 1) * 5));
for (let j = 0; j < 5; j++) {
let cell = {};
cell[slicedArray[j]] = false;
row[j] = cell;
}
board[i] = row;
}
return board;
}
I want to keep the structure like this:
Board object will have exactly 5 rows and 1 row has exactly 5 items. And in the future I need to iterate those items to find the random value that I had assigned before. I thought it is faster to use objects than arrays. I hope I am correct.

JavaScript - Combine two arrays item by item

I have two arrays of arrays where the first contains the location name and the second contains the location latitude and longitude values. Each item in each array corresponds to it's counterpart in the other and both arrays have the same number of items like so:
var arr1 = [['Location #1'],['Location #2']];
var arr2 = [['36.1978319','-83.02365759999999'],['38.679842','-121.7457402']];
What I need is a combined array of the two sets of items, but not concatenated like so:
var arr3 = [['Location #1','36.1978319','-83.02365759999999'],
['Location #2','38.679842','-121.7457402']];
The only way I can think of doing this would be with like a combined for loop, but I can't get the syntax correct and not sure this is even possible... something like this:
for ((var a = 0; a < arr1.length; a++) && (var b = 0; b < arr2.length; b++)) {
arr3.push(arr1[a] + ',' + arr2[b]);
}
Is there a way to solve this problem with pure javascript?
I suggest Array.map for its shortness:
var arr1 = [['Location #1'], ['Location #2']];
var arr2 = [['36.1978319', '-83.02365759999999'], ['38.679842', '-121.7457402']];
var combined = arr1.map((element, i) => element.concat(arr2[i]));
console.log(combined);
For a more generic solution (combining an arbitrary number of arrays), refer to Javascript equivalent of Python's zip function
If the two arrays really are equal in length, and correspond in index. This is all you need:
for (var a = 0; a < arr1.length; a++) {
arr3.push(arr1[a] + ',' + arr2[a]);
}
You are trying to combine 2 contors inside a for loop :).
You want to do this:
var resultArray = new Array();
for (var i = 0; i < arr1.length; i++) {
resultArray.push([arr1[i], arr2[i][0], arr2[i][1]]);
}

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

javascript split without losing first element (not RegEx)

I have a string containing ones and zeros split by "," and ";".
var x = "1,1,0;1,0,0;1,1,1;"; x.split(";");
This wil output an array with just two strings: 1,0,0 and 1,1,1.
What I want is to put all of these numbers in a two dimensional array:
1 1 0
1 0 0
1 1 1
If there is a smarter way than just split the string, please let me know.
Otherwise, please tell me how to fix the problem above.
You need to put quotes around your string.
Commentors are correct, your array contains all 3 strings. did you forget that array indices start at 0, not 1?
x.split does not modify x, it returns an array
You probably want something like this
var str = "1,1,0;1,0,0;1,1,1";
var arr = str.split(";");
for (var i = 0, len = arr.length; i < len; i++)
{
arr[i] = arr[i].split(",");
}
and to verify the result
for (var i = 0, len = arr.length; i < len; i++)
{
for (var j = 0, len2 = arr[i].length; j < len2; j++)
{
document.write(arr[i][j] + " | ");
}
document.write("<br>");
}
given the string:
var x = "1,1,0;1,0,0;1,1,1";
you can get a two dimensional array of zeros and ones this way:
var st = x.split(";")
var twoDimensionalArray = st.map(function(k){
return k.split(",");
});
of course, thanks to JS method chaining, you can do the whole thing this way:
var twoDimTable = x.split(";").map(function(k){
return k.split(",");
});
the result:
[
["1","1","0"],
["1","0","0"],
["1","1","1"]
]
well, to get the result as
[
[1,1,0],
[1,0,0],
[1,1,1]
]
you can do a loop and for each value k within the array do k = +k;
and you will get numbers instead of strings. However, JavaScript will do the casting
for you when you use these values within an operation with a number.

Find all occurrences of one 2D array inside another 2D array

In JavaScript, I'm trying to find all matching coordinates of this 2D integer array:
inside this 2D integer array, with overlapping sub-arrays being counted:
Each image represents a 2D JavaScript integer array, and the black pixels correspond to 1, and the yellow pixels correspond to 0, but I depicted the arrays this way so that they would be easier to visualize.
So how can I find all matches of the array inside the array ?
Here's the function I'm trying to implement:
findAllMatchesOfOne2DArrayInsideAnother2DArray(containedArray, containingArray){
//find all matching coordinates of containedArray inside containingArray, and return a 2D array of coordinates
}
Here is a way to get all occurances of any given 2D array inside another 2D array. It is assumed that all subarrays have the same dimension (nothing like [[1,0,0],[1,0]]).
var x = [[0,1,0,0,0,0,0],
[1,1,1,0,0,1,0],
[0,1,0,0,1,1,1],
[0,0,0,0,0,1,0],
[0,0,1,0,0,0,0],
[0,1,1,1,0,0,0],
[0,0,1,0,0,0,0]];
var y = [[0,1,0],[1,1,1],[0,1,0]];
var res = [];
for (var i = 0; i < x.length - y.length + 1; i++) {
for (var k = 0; k < x[0].length - y[0].length + 1; k++) {
var count = 0;
for (var l = 0; l < y.length; l++) {
for (var m = 0; m < y[l].length; m++) {
count += Math.abs(y[l][m] - x[i + l][k + m]);
}
}
if (count === 0) {
res.push([i, k]);
}
}
}
The array res will contain the "coordinates" of the top-left corner of each match. I'm sure you'll find better performing algorithms but this one seems to work :)

Categories

Resources