Skip to content

sumBy returns boolean instead of number when summing booleans #5985

@johnmasonyxe

Description

@johnmasonyxe

description:

when using _.sumBy on an array of objects with boolean values, the result is a boolean when the array contains only one item

reproduction

run this code on https://playcode.io/lodash:

import _ from 'lodash';

const result = _.sumBy([{ bool: true }], 'bool');

console.log(_.VERSION);         // 4.17.21
console.log(result);            // expected: 1, actual: true
console.log(typeof result);     // expected: 'number', actual: 'boolean
console.log(result === true);   // expected: false, actual: true
console.log(result === 1);      // expected: true, actual: false

expected behaviour
lodash should coerce boolean values to numbers (true → 1, false → 0) consistently, even for single-item arrays.

notes
for quick fix replace

_.sumBy([{ bool: true }], 'bool')

with

_.filter([{ bool: true }], item => item.bool).length

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions