@pengzhanbo/utils - v3.4.1
    Preparing search index...

    Function differenceBy

    • Computes the difference between two arrays after mapping their elements through a provided function.

      This function takes two arrays and a mapper function. It returns a new array containing the elements that are present in the first array but not in the second array, based on the identity calculated by the mapper function.

      Essentially, it filters out any elements from the first array that, when mapped, match an element in the mapped version of the second array.

      计算两个数组在通过提供的函数映射其元素后的差异。

      此函数接收两个数组和一个映射函数。它返回一个新数组,包含那些存在于第一个数组中但不在第二个数组中的元素, 基于映射函数计算出的标识。

      本质上,它会过滤掉第一个数组中那些在映射后与第二个数组映射版本中元素匹配的元素。

      Type Parameters

      • T

        The type of elements in the first array. 第一个数组中元素的类型

      • U

        The type of elements in the second array. 第二个数组中元素的类型

      Parameters

      • firstArr: readonly T[]

        The first array. 第一个数组

      • secondArr: readonly U[]

        The second array. 第二个数组

      • mapper: (value: T | U) => unknown

        The mapper function to transform elements. 用于转换元素的映射函数

      Returns T[]

      A new array containing the elements that are present in the first array but not in the second array. 包含存在于第一个数组中但不在第二个数组中的元素的新数组

      const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]
      const array2 = [{ id: 2 }, { id: 4 }]
      const mapper = item => item.id
      const result = differenceBy(array1, array2, mapper)
      // -> [{ id: 1 }, { id: 3 }]
      const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]
      const array2 = [2, 4]
      const mapper = item => (typeof item === 'object' ? item.id : item)
      const result = differenceBy(array1, array2, mapper)
      // -> [{ id: 1 }, { id: 3 }]