Check if array contains all elements of another array

前端 未结 5 1205
后悔当初
后悔当初 2020-11-30 08:27

I want a function that returns true if and only if a given array includes all the elements of a given "target" array. As follows.

const         


        
5条回答
  •  情歌与酒
    2020-11-30 09:20

    You can try with Array.prototype.every():

    The every() method tests whether all elements in the array pass the test implemented by the provided function.

    and Array.prototype.includes():

    The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

    var mainArr = [1,2,3];
    function isTrue(arr, arr2){
      return arr.every(i => arr2.includes(i));
    }
    console.log(isTrue(mainArr, [1,2,3]));
    console.log(isTrue(mainArr, [1,2,3,4]));
    console.log(isTrue(mainArr, [1,2]));

提交回复
热议问题