Array Subset
Learn how to tell if two arrays contain the same values. We'll discuss how to deal with both primitive values and objects and we'll go over how a JavaScript Map helps us with this problem.
We'll cover the following...
Array Subset
Instructions
Write a function that accepts two parameters, both arrays. The arrays can have both strings and numbers. Return true
if the second array is a subset of the first.
In other words, determine if every item in the 2nd array is also present somewhere in the 1st array.
Input: Array of Numbers & Strings, Array of Numbers & Strings
Output: Boolean
Examples
arraySubset([2, 1, 3], [1, 2, 3]); // -> true
arraySubset([2, 1, 1, 3], [1, 2, 3]); // -> true
arraySubset([1, 2], [1, 2, 3]); // -> false
arraySubset([1, 2, 3], [1, 2, 2, 3]); // -> false
Hints
- This problem has multiple solutions with different time complexities.
- We’ll need to consider how to deal with repeats, such as when an item is present twice.
Press + to interact
function arraySubset(arr, sub) {// Your code here}
Solution 1
Press + to interact
function arraySubset(arr, sub) {if(sub.length > arr.length) {return false;}for(let i = 0; i < sub.length; i++) {const arrIndex = arr.indexOf(sub[i]);if(arrIndex === -1) {return false;}delete arr[arrIndex];}return true;}
...