Search code examples
javascriptarrayslodash

Lodash How to verify if a property are all equal in array if I don't have the property to exclude


let's say I have this aray of employee data

var service = [{
        AssignedEmployeeInternalID: "8000000011",
        AssignedEmployeeUUID: "00000000-0001-1EE1-82C1-8379F1C4462E",
        BillableIndicator: true,
        BusinessPartnerFormattedName: "Sébastien Brun",
        EndDateTime: null,
        EndDatetimeZoneCode: "UTC",
        Info: "-N/A",
        InternalID: "",
        ObjectID: "00163E0E46241EE988E20C5E4033E0BE",
        ParentObjectID: "00163E0306801ED287F1C8E9CDFA9E4A",
        PeriodPlansArray: [],
        PlannedWorkQuantity: "0.00000000000000",
        PlannedWorkQuantityunitCode: "HUR",
        PlannedWorkQuantityunitCodeText: "",

    },
    {
        AssignedEmployeeInternalID: "8000000011",
        AssignedEmployeeUUID: "00000000-0001-1EE1-82C1-8379F1C4462E",
        BillableIndicator: false,
        BusinessPartnerFormattedName: "Sébastien Brun",
        EndDateTime: null,
        EndDatetimeZoneCode: "UTC",
        Info: "-N/A",
        InternalID: "",
        ObjectID: "00163E0E46241EE988E20C5E4033E0BE",
        ParentObjectID: "00163E0306801ED287F1C8E9CDFA9E4A",
        PeriodPlansArray: [],
        PlannedWorkQuantity: "0.00000000000000",
        PlannedWorkQuantityunitCode: "HUR",
        PlannedWorkQuantityunitCodeText: "",

    },
    {
        AssignedEmployeeInternalID: "8000000011",
        AssignedEmployeeUUID: "00000000-0001-1EE1-82C1-8379F1C4462E",
        BillableIndicator: true,
        BusinessPartnerFormattedName: "Sébastien Brun",
        EndDateTime: null,
        EndDatetimeZoneCode: "UTC",
        Info: "-N/A",
        InternalID: "",
        ObjectID: "00163E0E46241EE988E20C5E4033E0BE",
        ParentObjectID: "00163E0306801ED287F1C8E9CDFA9E4A",
        PeriodPlansArray: [],
        PlannedWorkQuantity: "0.00000000000000",
        PlannedWorkQuantityunitCode: "HUR",
        PlannedWorkQuantityunitCodeText: "",
    }
]

How to verify that AssignedEmployeeInternalID is the same in all the array ?

so far I came up with this :

result =  _.differenceBy(service, [{ 'AssignedEmployeeInternalID': "8000000011" }], 'AssignedEmployeeInternalID'); 

but what if I don't have the value to exclude (I can't know in advance the AssignedEmployeeInternalID value )

I want to dynamically verify that the property are all the same


Solution

  • You could use uniqBy (see documentation https://lodash.com/docs/4.17.15#uniqBy) and then if the length of the resulting array is 1, all array items have the same value for AssignedEmployeeInternalID:

    var uniqueByID = _.uniqBy(service, 'AssignedEmployeeInternalID');
    var allMatch = uniqueByID.length === 1;