0

I need to avoid getting duplicate values when I assign a value like this:

 hoursWorkedHelper : function(timeSheets){
        const hoursWorkedByContact = new Map();   
    if(timeSheets){                           
        timeSheets.forEach(timeSheet => {
            let copy = Object.assign({}, timeSheet);
            if(hoursWorkedByContact.has(copy.Contact__c)){
                copy.Name += ', ' + hoursWorkedByContact.get(copy.Contact__c).Name;
                copy.Project_Name__c += ', ' + hoursWorkedByContact.get(copy.Contact__c).Project_Name__c;
                console.log(copy.Project_Name__c);

            }
        })
    }
},

This is the line of code that gets duplicates when duplicate values are found:

    copy.Project_Name__c += ', ' + hoursWorkedByContact.get(copy.Contact__c).Project_Name__c;

For example, I want to avoid having this value on copy.Project_Name__c: "test, test, test 1", it should only be "test, test 1".

0

Instead of string manipulations use a Set to store unique values. Convert the final set into an array and use the join() method.

let projectNames = new Set();
timeSheets.forEach(timeSheet => {
    let copy = Object.assign({}, timeSheet);
    if(hoursWorkedByContact.has(copy.Contact__c)){
        projectNames.add(hoursWorkedByContact.get(copy.Contact__c).Project_Name__c);
    }
})

copy.Project_Name__c = [...projectNames].join(', ');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.