Modify an Array Stored in an Object BUG

I think this is a bug it won’t let me pass the challenge.

I have double check on my inspect element and it’s showing as 3 arrays successfully.


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) {
	userObj.data.friends.push(friend);
	return userObj;
};

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

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

What do the failing tests say?

there is no error on console

the only one is missing challenge goal was that

addFriend(user, “Pete”) should return [“Sam”, “Kira”, “Tomo”, “Pete”]

You’re returning the entire object. The requirement is to return the friends array. That’s why the test is failing. Your return value isn’t what is expected.

5 Likes

You have to use this :
return user.data.friends;

instead of this :
return userObj;

2 Likes

As it mentionned above , you have returned the entire object .

just return the friend object at last.

It is not bug , Try this

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

All the best

1 Like

FCC does stuff like this all the time and its super annoying… up until this point in the curriculum it taught us .push() was for arrays and mentioned nothing about it working with objects, so we have to waste time and effort looking stuff up for an hour instead of FCC just doing a better job at explaining the first time

It is for arrays, it doesn’t work with objects: userObj.data.friends is an array.

could you explain what makes the object an array?

It’s an array? I’m not quite sure how to explain it further - the thing in question is an array, so array methods work on it. myObj.data.friends is an array containing some names, it is not an object.

Edit:

This solution adds the friend’s name even when we already have it in the array. I suggest an alternate.

function addFriend(userObj, friend) {
  // change code below this line  
  if (userObj.data.friends.indexOf(friend) > 0) {
    return userObj.data.friends;
  } else if (userObj.data.friends.indexOf(friend) < 0) {
    userObj.data.friends.push(friend);
    return userObj.data.friends;
  }
  // change code above this line
}