JS Utils Kit
    Preparing search index...

    Function sum

    • Calculates the sum of values in an array.

      If a key is provided, the value from that property will be used for each item. Otherwise, items themselves are converted to numbers.

      Supports nested arrays of values.

      Type Parameters

      • T

        The type of items in the array.

      Parameters

      • items: (T | T[])[]

        The array of items to sum.

      • Optionalkey: keyof T

        Optional property key used to extract numeric values from each item.

      Returns number

      The sum of all numeric values.

      Values are converted using Number(). Non-numeric values will result in NaN.

      sum([1, 2, 3])
      // 6
      sum([[1, 2], [3, 4]])
      // 10
      sum([1, [2, [3, 4]]])
      // 10
      sum([{ price: 10 }, { price: 20 }], 'price')
      // 30
      sum([{ price: 10 }, [{ price: 20 }]], 'price')
      // 30
      sum([{ score: 5 }, { score: 7 }, { score: 8 }], 'score')
      // 20