DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

2

Modify an Array Stored in an Object (freecodecamp notes)

So in this particular exercise we are given an user obj as below;

let user = {
  name: 'Kenneth',
  age: 28,
  data: {
    username: 'kennethCodesAllDay',
    joinDate: 'March 26, 2016',
    organization: 'freeCodeCamp',
    friends: [
      'Sam',
      'Kira',
      'Tomo'
    ],
    location: {
      city: 'San Francisco',
      state: 'CA',
      country: 'USA'
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

Exercise

Write a function that adds a new friend to friends array in the user obj
They provide us the following function structure

  function addFriend(userObj, friend) {
       // Only change code below this line

     // Only change code above this line
    }
  console.log(addFriend(user, 'Peter Gregory'));
Enter fullscreen mode Exit fullscreen mode
//Answer 1
function addFriend(userObj, friend) {
return userObj.data.friends.push(friend)
}
//Answer 2
function addFriend(userObj, friend) {
userObj.data.friends.push(friend)
return userObj.data.friends
}
view raw addfriend.js hosted with ❤ by GitHub

Correct Answer? Answer 2

In attempt 1 we are returning what push function returns. Push returns the length of the array , instead of the array. Therefore we have to push the new friend and then return the array in the next line separately

Image description

Once you add Peter Gregory as a friend, remember to get him some asparagus!

Image description

Check the exercise here https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/modify-an-array-stored-in-an-object

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️