Is there a way to check if two arrays have the same elements?

前端 未结 4 1940
名媛妹妹
名媛妹妹 2021-01-18 04:56

Let say I have 2 arrays

firstArray  = [1, 2, 3, 4, 5];
secondArray = [5, 4, 3, 2, 1];

I want to know if they contain the same elements, whi

4条回答
  •  青春惊慌失措
    2021-01-18 05:40

    Not in Vanila Javascript but in Angular there is option to match two objects.

    angular.equals([1,2,3],[1,2,3])
    

    Determines if two objects or two values are equivalent. Supports value types, regular expressions, arrays and objects.

    See if this could help you.

    alert("Match result of [1,2,3] &  [1,2,3] is "+angular.equals([1,2,3],[1,2,3]));
    
    alert("Match result of [1,4,3] &  [1,2,3] is "+angular.equals([1,4,3],[1,2,3]));

    Click on Run Code snippet. If this solves your need please mark it as as Answer :)

    In case order is not important and array is of number type.

    var a1 = [1, 2, 3];
    var a2 = [2, 1, 3];
    //In case order is not important and array is of number type.
    alert(eval(JSON.stringify(a1).replace(/,/g, "+").replace(/\[/g, "").replace(/\]/g, "")) === eval(JSON.stringify(a2).replace(/,/g, "+").replace(/\[/g, "").replace(/\]/g, "")));

提交回复
热议问题