How to check if a multidimensional array has a specific array? - javascript

How to check if arrays has array?
var arrays = [[1, 1], [2, 2]];
var array = [1,1];
[1, 1] === [1, 1]; // false
arrays.includes(array); // false
arrays.indexOf(array); // -1

indexOf compares using strict equality (===). Your elements would have to be the exact same object.
so
var a = [1,1];
var b = [a,[1,2]];
b.indexOf(a)// 0
because a === a
but
b.indexOf([1,1])// -1
because [1,1] is a different object than a so they're not strictly equal.
MDN Docs
To do what you want to do you'll need to do something more involved. You can loop over the values and use something like whats in this question's answers to do the comparison

indexOf returns -1 if it does not find a match in the array. Your array a does not contain element b.
EDIT:
To clarify on what #JonathanLonowski said, the reason there is not a match is because you are doing a strict comparison, comparing the references, not the values.

<Array>.some method tests whether at least one array in the multi-dimensional array passes the test implemented by the provided function.
<Array>.every method tests whether all array items in the array pass the test implemented by the provided function.
These two methods combined make it possible to check if all the items of an array in the multidimensional one are worth those of that sought.
const checkArray = (arrays, array) => arrays.some(a => {
return (a.length > array.length ? a : array).every((_, i) => a[i] === array[i]);
});
const arrays = [[0, 1], [2, 2], [0, 3, 2, 1]];
[
[0, 1], // true
[2, 2], // true
[0, 3, 2, 1], // true
[1, 0, 3, 2, 1], // false
[2, 2, 1], // false
[0, 0], // false
[1, 2], // false
[0, 1, 2] // false
].forEach(array => {
console.log(checkArray(arrays, array));
});

Related

How to check the array within array if the value is the same on the newArray [duplicate]

This question already has answers here:
How to check if an array contains another array?
(6 answers)
javascript search array of arrays
(12 answers)
Closed 3 months ago.
How I can scan my array within array if there is equal array element.
I want to check if its true or false
// the array to be scan
const array = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
]
// the new array
const newArray = [0, 1, 2]
Based on anwser from how-to-compare-arrays-in-javascript,you just need to iterate the first array and then compare them
const array = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
]
// the new array
const newArray1 = [0, 1, 2]
const newArray2 = [0, 1, 3]
const checkArray = (array1,array2) => {
for(let arr of array1){
if(arr.length === array2.length && arr.every((v,i) => v === array2[i])){
return true
}
}
return false
}
console.log(checkArray(array,newArray1))
console.log(checkArray(array,newArray2))
You can use every method to check all the items.
array.filter((arr)=>arr.every((item,index)=>newArray[index]===item))
run a foreach or for loop with a combination of name.find(x => x.ref === value);
or use array.filter((arr)=>arr.every((item,index)=>newArray[index]===item))
const array = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
];
const newArray = [0, 1, 2]
let isPresent = false;
for (let i = 0; i < array.length; i++) {
if (JSON.stringify(array[i]) == JSON.stringify(newArray)) {
isPresent = true
break
}
}
console.log(isPresent)
After stringifying the array you are able to compare directly in js and If it matches I changed the boolean value to true.
In case you have any doubts feel free to comment.

How do I group repeated integers from a 2d array in javascript

I have an array of 3 value arrays, and I need to convert them into a set of arrays where each array is made up of the values which were common between arrays, so my input of
[[2,3,9], [1,4,7], [3,6,9], [1,7,5], [7,5,8], [9,6,10], [3,6,10], [1,8,5]]
becomes
[[2,3,6,9,10],[1,4,5,7,8]]
Order is not important. I've found similar questions such as Group same values in an array within an array in JS but it seems slightly different to my case, but I imagine using reduce is the way to go, but I don't entirely understand how. I have tried creating an object using the following format, but couldn't get from there to an answer:
{
vertex: 3,
triangles: [2,3,9], [3,6,9], [3,6,10]
}
Here is one algorithm. Take first item from array and check first item array has any common array. If they have common item, then merge it and move the merged array to first item of array. If no common item, then add to result array.
const merge = (arr) => {
const result = [];
while (arr.length > 0) {
let first = arr.shift();
const idx = arr.findIndex((items) =>
items.some((item) => first.includes(item))
);
if (idx !== -1) {
first = first.concat(arr[idx]);
arr.splice(idx, 1);
arr.unshift(first);
} else {
result.push(first);
}
}
return result.map(items => [...new Set(items)]);
};
const data = [
[2, 3, 9],
[1, 4, 7],
[3, 6, 9],
[1, 7, 5],
[7, 5, 8],
[9, 6, 10],
[3, 6, 10],
[1, 8, 5],
];
console.log(merge(data));

How do I match pairs in a 2 dimensional array in JavaScript?

I have an array with pairs of numbers and need to find matching pairs within the array
numberStore = [ [0,0],[1,1],[1,2],[1,3],[1,4],[1,5]... ]
I want to be able to find 1,4. Is there a way to find this array without relying on numberStore[4]?
Since you need to perform this search frequently, I would build a hashed set to avoid mapping and searching over and over. For example
const numberStore = [ [0,0],[1,1],[1,2],[1,3],[1,4],[1,5] ]
const hashedSet = new Set(numberStore.map(pair => pair.toString()))
// looks like ["0,0", "1,1", "1,2", "1,3", etc]
console.log([...hashedSet])
const search = (find) => {
return hashedSet.has(find.toString())
}
console.info('Find [1,4]', search([1,4]))
console.info('Find [4,1]', search([4,1]))
I've used Array.prototype.toString() as the hashing function but you could substitute anything there that creates a unique and comparable entity for each pair.
Use Array.prototype.find():
var numberStore = [
[0, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[1, 5]
];
var oneFour = numberStore.find(function([a, b]) {
return a == 1 && b == 4;
});
console.log(oneFour);
Or if you prefer ES6 arrow syntax:
var numberStore = [
[0, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[1, 5]
];
var oneFour = numberStore.find(([a, b]) => a == 1 && b == 4);
console.log(oneFour);
Another alternative is using the method some() to test elements for a condition.
var numberStore = [
[0,0],
[1,1],
[1,2],
[1,3],
[1,4],
[1,5]
];
var exists = numberStore.some(([a, b]) => a === 1 && b === 4);
console.log(exists ? "Pair [1,4] exists" : "Pair [1,4] don't exists");

Symmetric Difference of unknown number of arrays

Okay so I know there are multiple answers to this question but all of them use different approaches and I'm confused af rn.
The objective is to create a function that takes two or more arrays and returns an array of the symmetric difference of the provided arrays. The individual helper function is working fine but the code throws an error when I try to run it whole.
Here is my attempt:
function sym(args) {
let totalArguments = [...args];
var helper = function (arr1, arr2) {
return arr1.filter(item => arr2.indexOf(item) === -1).concat(arr2.filter(item => arr1.indexOf(item) === -1));
}
return totalArguments.reduce(helper);}
The input of sym([1, 2, 3],[2, 3, 4]) should be [1, 4]
Your code isn't working because you're only using the first argument:
function sym(args) {
let totalArguments = [...args];
This takes the first argument, args, and makes a shallow copy of the array - which doesn't accomplish anything because you aren't mutating anywhere anyway. If you wanted to accept a variable number of arguments, use argument rest syntax, to collect all arguments in an array:
function sym(...totalArguments) {
function sym(...totalArguments) {
var helper = function(arr1, arr2) {
return arr1.filter(item => arr2.indexOf(item) === -1).concat(arr2.filter(item => arr1.indexOf(item) === -1));
}
return totalArguments.reduce(helper);
}
console.log(sym([1, 2, 3], [2, 3, 4])) // [1, 4]
console.log(sym([1, 2, 3], [2, 3, 4], [0, 1])) // [0, 4], since 1 was duplicated
(There's no need to provide an initial value to the reducer)
Another option whose logic will probably be clearer to read and understand would be to iterate over all arrays and reduce into an object that keeps track of the number of times each number has occurred. Then, take the entries of the object, and return an array of the keys whose values are 1:
function sym(...args) {
const counts = args.reduce((a, arr) => {
arr.forEach((num) => {
a[num] = (a[num] || 0) + 1;
});
return a;
}, {});
return Object.entries(counts)
.filter(([, count]) => count === 1)
.map(([key]) => key);
}
console.log(sym([1, 2, 3], [2, 3, 4])) // [1, 4]
console.log(sym([1, 2, 3], [2, 3, 4], [0, 1])) // [0, 4], since 1 was duplicated

_.difference but allow duplicates

I'm trying to find the difference of two arrays but duplicates are allowed in the array and so I want to only remove them one at a time.
This is probably easier to show with an example. The _.difference function works like this:
_.difference([1, 1, 2], [1]); // returns [2]
But I would like to know if there is a function (preferably in underscore) that would instead do this:
_.difference2([1, 1, 2], [1]); // returns [1, 2]
_.difference2([1, 1, 2], [1, 1]); // returns [2]
And if there is not already a way to do this what would be an efficient way to make a mixin that does?
This mixin I came up with works.. but open to suggestions on how to improve it:
_.mixin({
remove: function(base, toRemove) {
var ret = [];
toRemove = _.clone(toRemove);
_.each(base, function(elem) {
var i = _.indexOf(toRemove, elem);
if(i < 0) {
ret.push(elem);
} else {
toRemove[i] = undefined;
}
});
return ret;
}
});
_.remove([1, 1, 2], [1]); // returns [1, 2]
_.remove([1, 1, 2], [1, 1]); // returns [2]

Categories