Modify an Array Stored in an Object (Simple way, but...)

Modify an Array Stored in an Object (Simple way, but...)
0

#1

Ok, I’m not using Object.keys().
But the function returns the array with the four names.
Nevertheless, it doesn’t pass .


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'
    }
  }
};

function addFriend(userObj, friend) {
  // change code below this line  
     // console.log(userObj.data.friends[3]);
      userObj.data.friends[3] = friend;
      //console.log(userObj.data.friends);
      return userObj.data.friends

  // change code above this line
}

console.log(addFriend(user, 'Pete'));


    
    

   

Your browser information:

User Agent is: Chrome/69.0.3497.100 .

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/modify-an-array-stored-in-an-object


#2

I don’t get it.
If I use ‘push’ instead, it works

Spoiler

userObj.data.friends.push(friend);
return userObj.data.friends


#3

When you do userObj.data[3] your setting the fourth item in the array to the passed argument (friend). This does what you want, but I guess the challenge requires you to use push. The method you used is very error prone and not recommended, since you need to know the length of the array and add to the correct index. Both of which could result in a nasty error if you mess up.

It’s very possible the internal implementation of the push method does what you did originally so just use push to keep things simple :smiley:


#4

Thanks a lot for the explanation and the extra info about error prone etc. It’s really good to know.
Thumbs up! :smile: