Search code examples
arrayselixircontains

Elixir: check array contains all the values of another array


I have two arrays:

arr1 = [1,2,3]
arr2 = [2,3] 

What is the most handy way to check that all values from the arr2 contains in arr1.


Solution

  • If you just want to check if all of the elements from one list are present in the other list, you can simply use -- using the shorter list at the left side of the operator:

    iex> [2, 3] -- [1, 2, 3]
    []
    

    If all of the elements from the first list are present in the second one, the result should be an empty list.

    Note, however, that this doesn't account for some cases, for instance, if your first list had a duplicate element, and the other list had the element, but just once, you wouldn't get an empty list:

    iex> [2, 3, 3] -- [1, 2, 3]
    [3]
    

    But in that case, technically, the second list does not contain all of the elements from the first one.

    If you would like to just check for presence of the elements, there are other simple solutions, like:

    Enum.all?([2, 3, 3], &Enum.member?([1, 2, 3], &1))
    

    Not sure about how efficient that is, though, as for each element of the first list you're checking if it's present in the second one (however, it will stop checking as soon as one element doesn't meet the condition, and the functions from Enum are typically optimized, so it might be good enough)

    And yet another option, would be to use MapSet.

    You can do:

    MapSet.subset?(MapSet.new([2, 3]), MapSet.new([1, 2, 3]))
    

    This will also work for duplicate elements, as MapSets work as sets, so you cannot have duplicate elements in them.