Compare arrays as (multi-) sets

前端 未结 8 1707
梦如初夏
梦如初夏 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:49

    Thanks everyone for sharing ideas! I've came up with the following

    function sameElements(a, b) {
        var hash = function(x) {
            return typeof x + (typeof x == "object" ? a.indexOf(x) : x);
        }
        return a.map(hash).sort().join() == b.map(hash).sort().join();
    }
    

    This isn't the fastest solution, but IMO, most readable one so far.

提交回复
热议问题