DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

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

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)