How to compare two arrays in node js?

前端 未结 7 1648
无人及你
无人及你 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:59

    The top answer is good, but I would also consider using Array.prototype:

    Array.prototype.equals = function (arr) {
        return this.length == arr.length && this.every((u, i) => u === arr[i]);
    }
    
    console.log([1,2,3].equals([1,2,3])); // true
    console.log([1,2,3].equals([1,3,3])); // false
    // BUT!
    console.log(["a",NaN,"b"].equals(["a",NaN,"b"])); // false, because NaN !== NaN
    

    If you want it to work for NaNs too and distinguish +0 and -0, better use this:

    Array.prototype.equals = function (arr) {
        function is(a, b) { // taken from the top answer
            return a === b && (a !== 0 || 1 / a === 1 / b) // false for +0 vs -0
                || a !== a && b !== b; // true for NaN vs NaN
        }
        return this.length == arr.length && this.every((u, i) => is(u, arr[i]));
    }
    
    console.log(["a",NaN,"b"].equals(["a",NaN,"b"])); // true
    

提交回复
热议问题