javascriptarraysvariablesscope

Why is my variable not working when passed as an argument?


For the person who is missing it, I am trying to add the year of death by using the reduce method for an array of objects.

For example:

{
name: "Carly",
yearOfBirth: 2018,
},
{
name: 'Carly',
yearOfBirth: 2018,
yearOfDeath: 2025
}

Why is using the passed variable causing the code to not function properly? I am new to this.

accum.push(passed = currentYear)

accum.push(person.yearOfDeath = currentYear)

See compared live examples with and without use of the variable.

const people = [
      {
        name: "Carly",
        yearOfBirth: 2018,
      },
      {
        name: "Ray",
        yearOfBirth: 1962,
        yearOfDeath: 2011,
      },
      {
        name: "Jane",
        yearOfBirth: 1912,
        yearOfDeath: 1941,
      },
    ]
    
    const newArray = people.reduce((accum, person) => {
      accum = []
        accum.push(person)
      
      let passed = person.yearOfDeath
      const currentYear = new Date().getFullYear();
      if (!passed) {
        accum.push(passed = currentYear)

console.log(accum)
      }
}, {})

const people = [
      {
        name: "Carly",
        yearOfBirth: 2018,
      },
      {
        name: "Ray",
        yearOfBirth: 1962,
        yearOfDeath: 2011,
      },
      {
        name: "Jane",
        yearOfBirth: 1912,
        yearOfDeath: 1941,
      },
    ]
    
    const newArray = people.reduce((accum, person) => {
      accum = []
        accum.push(person)
      
      const passed = person.yearOfDeath
      const currentYear = new Date().getFullYear();
      if (!passed) {
        accum.push(person.yearOfDeath = currentYear)

console.log(accum)
      }
}, {})


Solution

  • There's a few problems here.

    1. accum is supposed to be an array of elements. But you reset it to an empty array when do you this: accum = [].
    1. Incorrect use of = operator in accum.push() expects an item to be pushed into the array. You don't need the = operator.

    Here is the updated code:

    const people = [
        { name: "Carly", yearOfBirth: 2018 },
        { name: "Ray", yearOfBirth: 1962, yearOfDeath: 2011 },
        { name: "Jane", yearOfBirth: 1912, yearOfDeath: 1941 },
      ];
      
      const currentYear = new Date().getFullYear();
      
      const newArray = people.reduce((accum, person) => {
        // Create a copy of the person object to avoid modifying the original
        const updatedPerson = { ...person };
      
        
        if (!updatedPerson.yearOfDeath) {
          updatedPerson.yearOfDeath = currentYear;
        }
      
        accum.push(updatedPerson); // Push the updated object into the array
        return accum;
      }, []);
      
      console.log(newArray);