
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
isSubset of two arrays in JavaScript
We are required to write a JavaScript function that takes in two arrays of literals. The function should determine whether or not the second array is a subset of the first array, keeping these things in mind −
All values of array1 should be defined in array2
If duplicate values exist in array1, they should also take into account in array2.
For example, if arr1 = ["a", "a"] and arr2 = ["b", "a"] then isSubset is false because "a" appears twice in the first but only once in the second.
Example
The code for this will be −
const isSubset = (arr1, arr2) => { const count = (arr, ind) => { let i = arr.length; while (i−−) hash[arr[i]] = (hash[arr[i]] || 0) + ind; } const hash = {}; let i, keys; count(arr1, 1); count(arr2, −1); keys = Object.keys(hash); i = keys.length; while (i−−) { if (hash[keys[i]]){ return false; }; }; return true; } console.log(isSubset(["B", "A", "C", "A"], ["A", "B", "C", "A"])); console.log(isSubset(["B", "A", "C", "A"], ["A", "B", "C", "D"]));
Output
And the output in the console will be −
true false
- Related Questions & Answers
- Intersection of two arrays JavaScript
- Equality of two arrays JavaScript
- Reverse sum of two arrays in JavaScript
- issubset()-in-python
- Joining two Arrays in Javascript
- Combining two arrays in JavaScript
- Balancing two arrays in JavaScript
- Deviations in two JavaScript arrays in JavaScript
- Equality of two 2-D arrays - JavaScript
- Finding the continuity of two arrays in JavaScript
- Comparing corresponding values of two arrays in JavaScript
- Alternatively merging two arrays - JavaScript
- issubset() function in Python
- Combine two different arrays in JavaScript
- How to merge two arrays in JavaScript?
Advertisements