Compare values of two different arrays [duplicate] - javascript

This question already has answers here:
Check whether an array exists in an array of arrays?
(11 answers)
Closed 3 years ago.
My problem is about comparing the values of two different arrays, not to know if they are equal, but if a value in array A exists in array B.
Includes doesn't work, and I don't compare the length, only the values.
I spend many hours looking for an answer but found nothing precisely about this problem.
firstArray = [0,1];
secondArray = [[0,1],[0,2],[0,3],[1,1],[1,2],[1,3]];
How can I can compare firstArray and secondArray, to know if secondArray has the value of firstArray. It is like an equal comparison but only if the value of firstArray is in secondArray.
If it is, then the player can move on the board. The idea is that as long as firstArray value is one of secondArray value, the player can move. If not, no move possible.

You can stringify array items and compare:
var firstArray = [0,1];
var secondArray = [[0,1],[0,2],[0,3],[1,1],[1,2],[1,3]];
var res = secondArray.some(x => JSON.stringify(x) == JSON.stringify(firstArray));
console.log(res);

You can use Array.prototype.some() combined with Array.prototype.toString():
const firstArray = [0,1];
const secondArray = [[0,1],[0,2],[0,3],[1,1],[1,2],[1,3]];
const isFound = secondArray.some(a => a.toString() === firstArray.toString());
console.log(isFound);

Simply use JSON.stringify with some and sort():
var firstInSecond = secondArray.some(e => JSON.stringify(e.sort()) == JSON.stringify(firstArray.sort()));

Related

How to find two arrays differences and form differences in new array in JavaScript? [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 2 years ago.
How do I get differences between 2 arrays and form differences in new array?
arr1 = [1,2,3,4,5];
arr2 = [1,2,3,4];
newArr = [5];
Answer must be the same when arr1 and arr2 switch places.
We can use .includes()/ .indexOf() to resolve this q.
function diffArr(arr1, arr2) {
return arr1
.concat(arr2) //Join 2 arr into 1 new array
.filter(item => !arr1.includes(item) || !arr2.includes(item));
} //compare and remove arr1 & 2 with new array

How to Count Unique Arrays in a Multidimensional Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am looking for a way to not only find unique arrays within a multidimensional array, but also count how many times a particular array occurs.
For Example
var arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
var uniqueArrays = [];
var theCount = [];
// Code
???
// Results
uniqueArrays === [[1,2], [1,3], [1,4]]
theCount ==== [2, 1, 3]
Edit:
I didn't realize that I had to show my attempts of how I should solve a problem before I asked a question.
I do know how to count the length of an array use the length() method. I do know how to filter unique arrays from a multi-dimensional array. I did not post my attempts using those tools though because those two issues have been solved to death.
You can map each inner array to a stringified version of itself using .map(JSON.stringified). Now, using this new array, you can reduce it to an object which contains each stringified array as a key, and keeps the number of occurrences as its value. While reducing, you can check whether or not the object's key has already been set using a[k] = (a[k] || 0)+1. If it has already been set, it will use the current number stored at the key and increment it by 1, if it hasn't already been set it will set it equal to zero, and then increment it by 1 (which acts as the default value for any new keys (i.e newly seen arrays)).
Lastly, you can get the keys from your object which represent each unique array as strings using Object.keys(), and parse each back into a non-stringified array using JSON.parse. You can get the counts from your array by using Object.values() as this will get all the values (ie: the counters) of your reduced object and put them into an array.
See example below:
const arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
const arr_str = arr.map(JSON.stringify);
const arr_map = arr_str.reduce((a, k) => (a[k] = (a[k] || 0) + 1, a), {});
const uniqueArrays = Array.from(Object.keys(arr_map), JSON.parse);
const theCount = Object.values(arr_map);
console.log(uniqueArrays);
console.log(theCount);
you can use below code
var arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
var uniqueArrays = [];
var theCount = [];
var test = [], obj ={};
arr.forEach(val => {
if(test.indexOf(val.toString()) == -1){
test.push(val.toString());
obj[val.toString()] = 1;
uniqueArrays.push(val);
}else{
obj[val.toString()] += 1;
}
})
theCount = Object.values(obj);
console.log(uniqueArrays);
console.log(theCount);
Hope it will help you.

perform test on JS array to see if it contains another array of values [duplicate]

This question already has answers here:
How to check whether multiple values exist within an Javascript array
(11 answers)
Closed 4 years ago.
I have found some solutions on this site and others such as Array.prototype.includes() and Array.prototype.indexOf() and jQuery.inArray().
Each of these solutions are well suited to check if a single value 'x' is in array ['x','y','z'].
My question is: How can I test to see if multiple values are present in an array. In other words, is array X in array Y?
For example:
Is ['a','e','f'] in ['a','b','c','d','e','f','g']? Result: True.
Is ['a','e','z'] in ['a','b','c','d','e','f','g']? Result: False.
EDIT:
Ideally the solution would work as far back as IE 10.
This is fairly concise and does what you want:
const array1 = ['a','b','c','d','e','f','g'];
const array2 = ['a','e','f'];
console.log(array2.every(currentValue => array1.includes(currentValue)));
Everything after the first 3 lines is just for testing and to show how to use this function. One case is true the other is false.
Array.prototype.containsAll = function(values) {
return values.every((val) => this.indexOf(val) !== -1);
}
var array = ['a','b','c','d','e','f','g'];
var testA = ['a', 'e', 'f'];
var testB = ['a', 'e', 'z'];
var testC = ['x', 'a'];
var res = array.containsAll(testA);
console.log(res);
var res = array.containsAll(testB);
console.log(res);
var res = array.containsAll(testC);
console.log(res);
Added a function to the Array Prototype which is handling your problem.

optimal solution to filter elements from array [duplicate]

This question already has answers here:
Remove all elements contained in another array [duplicate]
(17 answers)
Closed 5 years ago.
I have an array of animals arr = ['cat','dog','elephant','lion','tiger','mouse']
I want to write a function remove(['dog','lion']) which can remove the elements from arr, and returns a new array, what is the best and optimal solution?
example:
arr = ['cat','dog','elephant','lion','tiger','mouse']
remove(['cat', 'lion'])
arr should get changed to
arr = ['dog','elephant','tiger','mouse']
Note: No Mutations
you can just use filter()
var arr = ['cat','dog','elephant','lion','tiger','mouse'];
var newArr = arr.filter(x => !['cat', 'lion'].includes(x))
console.log(newArr);

How can I compare two JavaScript arrays in order to determine if they have identical values? [duplicate]

This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 8 years ago.
I don't want to compare the two arrays as a whole, I specifically want to check if the 2nd array has any values that match a value in the first one. I then want to return the value that matches in both.
If I'm not mistaken, comparing two arrays as a whole would be done like this:
array1 = [1,2,3];
array2 = [1,3,4];
console.log(JSON.encode(array1)==JSON.encode(array2));
So in this case, I would want to check if array2 has any matching values to array one, not if they both are equivalent. Any help is appreciated!
var array1 = [1, 2, 3],
array2 = [1, 3, 4];
var AnyItemsOfArray1InArray2 = array1.some(function(item) {
return array2.indexOf(item) > -1;
});
console.log(AnyItemsOfArray1InArray2);
var ItemsOfArray1InArray2 = array1.filter(function(item) {
return array2.indexOf(item) > -1;
});
console.log(ItemsOfArray1InArray2);

Categories

Resources