Compare arrays as (multi-) sets

前端 未结 8 1703
梦如初夏
梦如初夏 2021-01-04 21:42

I\'m looking for an efficient way to find out whether two arrays contain same amounts of equal elements (in the == sense), in any order:

foo = {         


        
8条回答
  •  春和景丽
    2021-01-04 21:55

    You can implement the following algorithm:

    • If a and b do not have the same length:
      • Return false.
    • Otherwise:
      • Clone b,
      • For each item in a:
        • If the item exists in our clone of b:
          • Remove the item from our clone of b,
        • Otherwise:
          • Return false.
      • Return true.

    With Javascript 1.6, you can use every() and indexOf() to write:

    function sameElements(a, b)
    {
        if (a.length != b.length) {
            return false;
        }
        var ourB = b.concat();
        return a.every(function(item) {
            var index = ourB.indexOf(item);
            if (index < 0) {
                return false;
            } else {
                ourB.splice(index, 1);
                return true;
            }
        });
    }
    

    Note this implementation does not completely fulfill your requirements because indexOf() uses strict equality (===) internally. If you really want non-strict equality (==), you will have to write an inner loop instead.

提交回复
热议问题