How to compare two arrays in node js?

前端 未结 7 1559
无人及你
无人及你 2021-01-12 07:42

I am having two arrays, how can i compare the two arrays at single shot.

   var arr1= [\"a\",\"b\",\"c\"];
   var arr2 = [\"a\",\"c\",\"d\"]

   if(arr1 == a         


        
7条回答
  •  执笔经年
    2021-01-12 07:52

    [ES6]

    Top answer is good & enough.

    But when you just want to compare its values are same you have to sort it before. here's no need sort code.

    if(arr1.length == arr2.length && arr1.every((v) => arr2.indexOf(v) >= 0)) {
        console.log(true);
    } else {
        console.log(false);
    }
    

    And.. I think using a 'some' instead of 'every' is better.

    If those are not same, 'some' gives you a early exit. - very little early but early ;)

    if(arr1.length == arr2.length && !arr1.some((v) => arr2.indexOf(v) < 0)) {
        console.log(true);
    } else {
        console.log(false);
    }
    

提交回复
热议问题