Check if an array of object is exactly equal to another array that contains one of its property
as @mplungjan mentiond, you can use Every:
let fixed = ["123", "456", "789"];
let variableArray1 = [{
name: "Joe",
id: "123"
}, {
name: "Joe",
id: "456"
}, {
name: "Joe",
id: "789"
}];
let variableArray2 = [{
name: "Joe",
id: "123"
}, {
name: "Joe",
id: "456"
}, {
name: "Joe",
id: "001"
}]
let containsAll1 = variableArray1.every(elem => fixed.includes(elem.id));
let containsAll2 = variableArray2.every(elem => fixed.includes(elem.id));
console.log(containsAll1, containsAll2);
JavaScript: How can i check if an array contains elements in common with a second array?
A quick solution could be something like this:
const pcNumbers = [1,2,3,8,5];
const userNumbers = [1,2,7,8,9];
const newArr = [];
for (let i = 0; i < pcNumbers.length; i++) {
for (let j = 0; j < userNumbers.length; j++) {
if (pcNumbers[i] === userNumbers[j]) {
newArr.push(pcNumbers[i])
}
}
};
console.log(`These are in common: ${newArr.join(', ')}`)
This will result in:
These are in common: 1, 2
Determine if one array contains all elements of another array, including any duplicates
const isMultiSubset = (target, value) => {
const occurences = new Map;
for(const entry of target)
occurences.set(entry, (occurences.get(entry) ?? 0) + 1);
for(const entry of value)
if (occurences.has(entry))
occurences.set(entry, occurences.get(entry) - 1);
return [...occurences.values()].every(count => count <= 0);
};
By using a Map to count occurences this can be solved in O(n + m).
Check if an array contains 2 or more elements of another array in JavaScript
Firstly, you can use array#filter
combined with array#includes
to find all items in arr1 in arr2.
Then check the length of result.
let arr1 = [1, 2, 3];
let arr2 = [2, 3];
let result = arr1.filter(v1 => arr2.includes(v1));
console.log(result.length >= 2);
Related Topics
How to Add Number of Days to Today'S Date
For Loop For Htmlcollection Elements
How Does This Object Method Definition Work Without the "Function" Keyword
Queryselector and Queryselectorall VS Getelementsbyclassname and Getelementbyid in JavaScript
Screen Styling When Virtual Keyboard Is Active
Jquery or JavaScript - How to Disable Window Scroll Without Overflow:Hidden;
How to Build & Deploy a Samsung Smarttv App Without the Ide (E.G: on Linux)
Cross-Browser JavaScript Xml Parsing
How to Deep Clone in JavaScript
Difference Between Synchronous and Asynchronous Programming (In Node.Js)
How to Use Backslashes (\) in a String
Converting Between Strings and Arraybuffers
Hide Scrollbar and Show on Hover Like Facebook's New Chat Sidebar