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

Check if array contains in an object property all elements of another array in js

You can use map and every for this. With map you extract the ids into an array (keys). With every you check if for every element in array2 a condition holds.

let array1 = [
{id: 123, name: "Name of item"},
{id: 456, name: "Other name"}
]
let array2 = [123, 456]

const keys = array1.map(el => el.id)
console.log(array2.every(id => keys.includes(id)))

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

check if an javascript array contains all of the values of another array

Your code does not work, because it always returns anything (if not false, then true) in first iteration (reason: return true statement is in for loop). Try this:

let arrayContainsArray = (a, b) => {  let a_array = a.split(" ")  let b_array = b.split(" ")
for (let i = 0; i < b_array.length; i++) { if (a_array.includes(b_array[i])) { let index = a_array.indexOf(b_array[i]) a_array.splice(index, 1) } else { return false } } return true}
console.log(arrayContainsArray('two times three is not four', 'two times two is four'));console.log(arrayContainsArray('A B C D', 'B B C D'));console.log(arrayContainsArray('apple banana orange mango', 'banana orange'));

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


Related Topics



Leave a reply



Submit