lorstevens
12/12/2019 - 8:52 PM

Reduce- replay property in array of objects

// Initial array of people with wrong first names
const people = [
    { firstName: 'michael', lastName: 'Scott' },
    { firstName: 'jim', lastName: 'Halpert' },
    { firstName: 'dwight', lastName: 'Schrute' }
];

// Callback function which will fix the first name of each person
const fixFirstNameCallbackFunction = function (accumulator, currentElement) {
    // Generate a correct person object by changing the first letter of the first name
    const fixedPerson = {
        ...currentElement,
        firstName:
            currentElement.firstName.charAt(0).toUpperCase() +
            currentElement.firstName.slice(1)
    };

    // Return the value for the next step by using the array from the previous step and
    // add the new fixed person
    return [...accumulator, fixedPerson];
};

// Use the callback function in the reduce function
const fixedPeople = people.reduce(
    fixFirstNameCallbackFunction,
    [] // Initial value is an empty array which will be filled with the corrected people
);

console.dir(fixedPeople);