difference_by()
Creates an array of values not included in the other given arrays using SameValueZero for equality comparisons.
Implementation
Args: array (List[T]): The array to inspect. values (List[T]): The values to exclude. iteratee (Optional[Callable[[T], Any]]): The iteratee to transform values. Returns: List[T]: Returns the new array of values not included in the other given arrays.
Example
difference_by([2.1, 1.2, 2.3], [2.3, 3.4], key=lambda x: round(x))
Expected output: [1.2]
Source Code
def difference_by(array: List[T], *args) -> List[T]:
if not args:
return list(array)
# last arg may be iteratee
iteratee = args[-1]
if callable(iteratee) or isinstance(iteratee, str):
values = [] if len(args) == 1 else args[0]
else:
iteratee = None
values = args[0]
if iteratee is None:
def key(x): # type: ignore
return x
elif isinstance(iteratee, str):
def key(x):
return (
x.get(iteratee) if isinstance(x, dict) else getattr(x, iteratee, None)
)
else:
key = iteratee # type: ignore
other_keys = {key(v) for v in (values or [])}
return [item for item in array if key(item) not in other_keys]