Home > Back-end >  Check if an array contains all of the elements of another array
Check if an array contains all of the elements of another array

Time:02-05

So I'm making a program that has 2 arrays: Array1: the input form the user, and Array2: an array that the program needs to check. If Array2 has includes all of the elements of Array1, then de program does something.

Oh and I'm making it in html javascript, and not node.js

if(Array1 != ""){
        for(i =0; i < Array2.length; i  ){
            var currentelem = Array2[i].split(" ");
            for(j=0; j < currentelem.length; j  ){
                if(Array1.includes(currentelem[j])){
                    alert("asd")
                }
            }
        }
    }

CodePudding user response:

You can combine the .every() and .includes() methods:

let array1 = [1,2,3],
    array2 = [1,2,3,4],
    array3 = [1,2];

let checker = (arr, target) => target.every(v => arr.includes(v));

console.log(checker(array2, array1));  // true
console.log(checker(array3, array1));  // false

Oh and this was not Original, all the credit goes to user Mohammad Usman you can check him out on https://stackoverflow.com/users/5933656/mohammad-usman

CodePudding user response:

You could take an object and count the items and return false if some item has some count.

const
    check = (a, b) => {
        const
            count = (c, i) => v => c[v] = (c[v] || 0)   i,
            counts = {};
        a.forEach(count(counts, 1));
        b.forEach(count(counts, -1));
        return !Object.values(counts).some(Boolean);
    };
    

console.log(check([], [1]));
console.log(check([1], []));
console.log(check([1], [1]));
console.log(check([1, 1], [1]));
console.log(check([1, 1], [1, 1]));

CodePudding user response:

function arrayContains(x,y) {
  // returns true if array x contains all elements in array y
  return !x.reduce((y,e,t)=>
    (t=y.indexOf(e),t>=0&&y.splice(t,1),y),[...y]).length
}

console.log(arrayContains([1,2,3,4,4],[1,2,4,4]))
console.log(arrayContains([1,2,3,4],  [1,2,4,4]))
console.log(arrayContains([1,2,3,4,4],[1,2,4,4,5]))

  • Related