Array Include Any Value from Another Array

Array include any value from another array?


(cheeses & foods).empty?

As Marc-André Lafortune said in comments, & works in linear time while any? + include? will be quadratic. For larger sets of data, linear time will be faster. For small data sets, any? + include? may be faster as shown by Lee Jarvis' answer -- probably because & allocates a new Array while another solution does not and works as a simple nested loop to return a boolean.

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

search an array with value from another array in javascript

You could implement a nested loop.





for(let i = 0; i < order.length; i++) {
for(let j = 0; j < elements.length; j++) {
if( order[i] == elements[j] ) {
return orders[i]
}
}
}

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

Array include every value from another array?

You can simply subtract one array from another, if the result is an empty array, all values are contained:

cheeses = %w[brie feta]
foods = %w[feta pizza brie bread]
(cheeses - foods).empty?
#=>true

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

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



Related Topics



Leave a reply



Submit