Determine If One Array Contains All Elements of Another Array

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).

How to determine if one array contains all elements of another array

a = [5, 1, 6, 14, 2, 8]
b = [2, 6, 15]

a - b
# => [5, 1, 14, 8]

b - a
# => [15]

(b - a).empty?
# => false

Determine if one array contains all elements of another array

class Array
def contains_all? other
other = other.dup
each{|e| if i = other.index(e) then other.delete_at(i) end}
other.empty?
end
end

Check to see if an array contains all elements of another array, including whether duplicates appear twice

Try creating this function:


function containsAll (target, toTest) {

const dictionary = {}

target.forEach(element => {
if (dictionary[element] === undefined) {
dictionary[element] = 1;
return;
}
dictionary[element]++;
});

toTest.forEach(element => {
if (dictionary[element] !== undefined)
dictionary[element]--;
})

for (let key in dictionary) {
if (dictionary[key] > 0) return false;
}

return true;

}

Then invoke it like this:

const arr1 = [1, 2, 2, 3, 5, 5, 6, 6]
const arr2 = [1, 2, 3, 5, 6, 7]

console.log(containsAll(arr1, arr2)) // returns false

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);

Finding if an array contains all elements in another array

You could check that the larger of the arrays outer contains every element in the smaller one, i.e. inner:

public static boolean linearIn(Integer[] outer, Integer[] inner) {

return Arrays.asList(outer).containsAll(Arrays.asList(inner));
}

Note: Integer types are required for this approach to work. If primitives are used, then Arrays.asList will return a List containing a single element of type int[]. In that case, invoking containsAll will not check the actual content of the arrays but rather compare the primitive int array Object references.



Related Topics



Leave a reply



Submit