How to check if array keys exist in multidimensional array? - javascript

I have an array like this:
var winArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[7, 5, 3]
];
And another array like this:
var Xarray = [1,2,3]
How can I check that the first array's index 0 contains my second array? Another issue is that the value order should not be regarded during the compression

Copy the arrays to new arrays, so that you can sort them, then compare each item in the arrays:
var a1 = winArray[0].slice(0);
var a2 = Xarray.slice(0);
var equal = a1.length == a2.length;
if (equal) {
a1.sort();
a2.sort();
for (var i = 0; i < a1.length; i++) {
if (a1[i] != a2[i]) {
equal = false;
break;
}
}
}
Demo: http://jsfiddle.net/Guffa/oa11qc4r/
If you mean that you want to search the array for a match, and not only compare the array at index 0, you would loop through the array and compare each array:
var a1 = Xarray.slice(0);
a1.sort();
var equal = false;
for (var j = 0; !equal && j < winArray.length; j++) {
var a2 = winArray[j].slice(0);
equal = a1.length == a2.length;
var index = j;
if (equal) {
a2.sort();
for (var i = 0; i < a1.length; i++) {
if (a1[i] != a2[i]) {
equal = false;
break;
}
}
}
}
Demo: http://jsfiddle.net/Guffa/oa11qc4r/1/

Might give this a shot. The function will return the index of the 'child array' if its found in the main data array. If its not found -1 will be returned.
var winArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[7, 5, 3]
];
var Xarray = [1,2,3];
function indexOfPredicate(data, value, predicate) {
if (typeof(predicate) !== 'function') {
throw "Predicate must be a function"
}
for(var x = 0; x < data.length; x++) {
if (predicate(data[x], value)) {
return x
}
}
return -1;
}
function indexOfMulti(data, value) {
return indexOfPredicate(data, value, function(a, b) {
if (a.length !== b.length) {
return false;
}
for(var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
})
}
var index = indexOfMulti(winArray, Xarray);
var contains = index > -1;
console.log(index);
console.log(contains);

Related

function that takes a nested array and element as an argument, return a new array, if a nested array doesn't contain element it will push it to newArr

function filteredArray(arr, elem) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; i++) {
if (arr[i][j] != elem) {
newArr.push(arr[i]);
}
}
}
return newArr;
}
console.log(filteredArray([
[3, 2, 3],
[1, 6, 3],
[3, 13, 26],
[19, 3, 9]
], 3));
How should I remove that error? If a nested array doesn't contain element it will push it to newArr.
You need to increment j in that inner loop.
You also need to find a way to check to see if elem has been found, and only if it's been found, to add the nested array to the output.
function filteredArray(arr, elem) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
let found = false;
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] === elem) {
found = true;
}
}
if (!found) newArr.push(arr[i]);
}
return newArr;
}
console.log(JSON.stringify(filteredArray([
[3, 2, 3],
[1, 6, 3],
[1, 6, 4],
[3, 13, 26],
[19, 3, 9]
], 3)));
A more modern method would be to filter out the arrays that where elem is not included:
function filteredArray(arr, elem) {
return arr.filter(inner => {
return !inner.includes(elem);
});
}
console.log(JSON.stringify(filteredArray([
[3, 2, 3],
[1, 6, 3],
[1, 6, 4],
[3, 13, 26],
[19, 3, 9]
], 3)));
function filteredArray(arr, elem) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] == elem) {
newArr.push(arr[i]);
}
}
}
return newArr;
}
console.log(filteredArray([
[3, 2, 3],
[1, 6, 2],
[3, 13, 26],
[19, 3, 9]
], 3));

How to use for loop to remove items from array of array without using js methods?

I'm using for loop to remove only 3 from array of array?
I have tried few conditional statements but it's not working for me.
let myArray = [
[1, 2, 3],
[5, 4, 3],
[3, 6, 7],
[3, 8, 9]
];
let newArray = [];
for (let i = 0; i < myArray.length; i++) {
if (myArray[i] !== 3) {
newArray.push(myArray[i]);
console.log(newArray);
}
}
I am expect the output 1,2,4,5,6,7,8,9, but actual output is with 3.
let myArray = [
[1, 2, 3],
[5, 4, 3],
[3, 6, 7],
[3, 8, 9]
];
let newArray = [];
for (let i = 0; i < myArray.length; i++) {
for(let j=0; j< myArray[i].length; j++) {
if (myArray[i][j] != 3) {
newArray.push(myArray[i][j]);
}
}
}
console.log(newArray);
myArray[i] is an array, you have to loop through the items of myArray[i] as well.
let myArray = [ [1, 2, 3], [5, 4, 3], [3, 6, 7], [3, 8, 9]];
let newArray = [];
for(let i=0; i<myArray.length; i++) {
for(let j=0; j<myArray[i].length; j++) {
if (myArray[i][j] != 3) {
newArray.push(myArray[i][j]);
}
}
}
console.log(newArray);
You have a two dimentional array but you are treating it like is one dimentional array.
Try the following:
let myArray = [
[1, 2, 3],
[5, 4, 3],
[3, 6, 7],
[3, 8, 9]
];
let newArray = [];
for (let i = 0; i < myArray.length; i++) {
newArray.push([]);
for (let j = 0; j < myArray[i].length; j++) {
if (myArray[i][j] != 3) {
newArray[i].push(myArray[i][j]);
}
}
}
console.log(newArray);
The problem is with your flow.
Here is what your code should look like:
var newArray = [];
var temp = [];
var myArray = [
[1, 2, 3],
[5, 4, 3],
[3, 6, 7],
[3, 8, 9]
];
for (var i = 0; i < myArray.length; i++) {
temp = [];
for( var j = 0; j < myArray[i].length; j++){
if (myArray[i][j] != 3) {
temp[j]= myArray[i][j];
}
}
newArray[i] = temp;
}
console.log(newArray);
This is a single loop approach by using a dynamic check of the length, depending on the actual loop purpose.
You could assign all values and take for the nested array a new index k to assign to the right index. This index is only incremented on a valid value.
var myArray = [[1, 2, 3], [5, 4, 3], [3, 6, 7], [3, 8, 9]],
newArray = [],
i, j, k;
for (i = 0; i < (myArray[j] || myArray).length; i++) {
if (j === undefined) {
j = i;
i = 0;
k = 0;
newArray[j] = [];
}
if (myArray[j][i] !== 3) {
newArray[j][k++] = myArray[j][i];
}
if (i + 1 >= myArray[j].length) {
i = j;
j = undefined;
}
}
console.log(newArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Is there a way to identify if an array matches with each set in the 2d array after looping through a 2d array for each element in an array?

I'm creating a tictactoe game and I'm trying to compare each set array within the winPattern 2d array to the placePieces array.
I've created loops to iterate through the winPattern 2d array for each placePieces array but because it doesn't recognize each array as a set and simply iterates through individual values, it doesn't work as intended.
const winPattern = [
//horizontal
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
//vertical
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
//diagonal
[0, 4, 8],
[2, 4, 6]
];
//positions that o or x would be in tictactoe
const placePieces = [0, 1, 2, 4, 8];
let count = 0;
nextPiece:
for (let i = 0; i < placePieces.length; i++) {
for (let j = 0; j < winPattern.length; j++) {
for (let n = 0; n < winPattern[0].length; n++) {
if (placePieces[i] === winPattern[j][n]) {
//Prints out the matches and mismatches
console.log(`It matches: Piece: ${placePieces[i]} //\\ Pattern: ${winPattern[j][n]}`);
continue nextPiece;
} else {
console.log(`It doesn't match: Piece: ${placePieces[i]} //\\Pattern: ${winPattern[j][n]}`);
}
}
}
}
I'm expecting the placePieces array to compare values with each SET of arrays in the winPattern 2d array.
This code should work to see if the users current array matches anything in the answers array -
var winPattern = [
//horizontal
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
//vertical
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
//diagonal
[0, 4, 8],
[2, 4, 6]
];
//positions that o or x would be in tictactoe
var placePieces = [0, 1, 2, 4, 8, ];
var count = 0;
function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
function checkMatch(arr){
for(var i = 0; i < winPattern.length; i++){
for(var j = 0; j < arr.length - 2; j++){
for(var k = j + 1; k < arr.length - 1; k++){
for(var l = k + 1; l < arr.length; l++){
var possibleAnswer = [arr[j], arr[k], arr[l]];
if(arraysEqual(possibleAnswer, winPattern[i])) return true;
}
}
}
}
return false;
}
This is assuming placePieces is sorted because it seemed like it was in your example. Hope this helps!

JavaScript array cross random number?

In the array randomly take three numbers, but the number of up and down the left and right non-adjacent (array cross random number)
This is my code, how can I optimize (get the number more evenly)?
Thanks~
array
var a = [
[0, 1],
[2, 3],
[4, 5],
[6, 7]
];
function select() {
var a = [
[0, 1],
[2, 3],
[4, 5],
[6, 7]
];
var lastSelect = -1;
for (var i = 0; i < a.length; i++) {
var index = getRandomNumber(lastSelect, a[i].length);
console.log(a[i][index]);
lastSelect = index;
}
}
function getRandomNumber(lastSelect, max) {
var random = Math.floor(Math.random() * max);
if (random == lastSelect) return getRandomNumber(lastSelect, max);
else return random;
}
select();
Javascript has a modulus operator %, that finds the remainder of division.
var a = [
[0, 1],
[2, 3],
[4, 5],
[6, 7]
];
function select() {
//generating random 0 or 1
var random = Math.round(Math.random());
for (var i = 0; i < a.length; i++) {
console.log(a[i][(i+random)%2]);// 0 or 1
}
console.log("-----------");
}
//test
for(var j=0;j<5;j+=1){
select();
}

Javascript Basic Logic - print each three and four cycle from 1 to n

I want to see the output like
[0, 1, 2]
[3, 4, 5, 6]
[7, 8, 9]
[10, 11, 12, 13]
[14, 15, 16]
...
recognize every three(a cycle) and four(b cycle) to do something.
I have only figure out some bad way I think like following:
var arr = [];
function a(n) {
var eachCycle = 7;
var aCycle = 3;
var bCycle = 0;
arr.push(0);
for (var i = 1; i < n; i += 1) {
if (i % eachCycle === aCycle || i % eachCycle === bCycle) {
if(i % eachCycle === aCycle) {
// print three column
} else if(i % eachCycle === bCycle) {
// print four column
}
console.log(arr);
arr.length = 0;
}
arr.push(i)
}
}
is there any good idea to improve this function for the output !?
Thanks
How about this:
function a(n)
{
// keep track of all the cycles
var total = [];
// hold values for the current cycle
var temp = [];
// cycle sizes
var cycleSizes = [3, 4];
// index of the current cycle
var currentCycleIndex = 0;
// iterate through numbers
for(var i = 0; i < n; ++i)
{
// push the value into the temp
temp.push(i);
// if the length of the temp array is the length we want for the current cycle then
if(temp.length == cycleSizes[currentCycleIndex])
{
// save the cycle data
total.push(temp);
// reset the cycle
temp = [];
// change the cycle
currentCycleIndex = currentCycleIndex ^ 1;
}
}
return total;
}
a(9);
[
[0, 1, 2],
[3, 4, 5, 6],
[7, 8]
];
a(17);
[
[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9],
[10, 11, 12, 13],
[14, 15, 16],
];

Categories

Resources