Tell us what’s happening:
please i tried to use concat() method.It seemed to work but FCC did not pass it. Pls can anyone tell the why?
Your code so far
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
return userObj.data.friends.concat(friend);
// change code above this line
}
console.log(addFriend(user, 'Pete'));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36
.
Challenge: Modify an Array Stored in an Object
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/modify-an-array-stored-in-an-object
The concat()
method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
You are returning a new array with all the correct values, but you haven’t actually altered the friends
array nested in userObj
.
2 Likes
As suggested by @colinthornton concate used to merge two or more arrays and will return a new array.
you can try using push array method for adding ‘friend’ to friends array.
userObj.data.friends.push(friend);
return userObj.data.friends;
2 Likes
Thanks @colinthornton for the helpful explanation! Glad to have you there! And more power to your elbow.
I cannot appreciate your help enough @natasha016. My journey into the programming world is made really real! thanks.
One of the big pushes for ES6 is “maintain data immutability!” What that means is, rather than changing the existing array, we should create a new one and simply point the userObj.data.friends
at that. An easy way, using ES6 operators? The spread
operator will work here:
userObj.data.friends = [...userObj.data.friends, friend]
// create a new array, spread the existing array in that, and add the new record to the end.
return userObj.data.friends;
Just suggesting, there’s always more than one way to skin a cat. 
1 Like