Record Collection Challenge array confusion - please help!

Record Collection Challenge array confusion - please help!
0

#1

SPOILER ALERT!!

Hey guys,

I’m a little confused on why my original code didn’t work (and man, did I try). Here is my original code that didn’t work:


function updateRecords(id, prop, value) {

if (prop != "tracks" && value !== ""){
  collection[id][prop] = value;
}

if (prop == "tracks" && value !== ""){
  
  if (collection[id][prop]){
  collection[id][prop].push(value);
} else {
   collection[id][prop] = []; //THIS IS WHERE I AM CONFUSED
   collection[id][prop] = value; // //THIS IS WHERE I AM CONFUSED
}
}
if (value === ""){
  delete collection[id][prop];
}

return collection;
}


When I changed my code in the above else statement to the following it worked, but I don’t know why - can anyone help explain why my original code didn’t work?


else {
collection[id][prop] = [];
collection[id][prop].push(value); //NOW IT WORKS?
}


Thanks!


#2

At first you assigned it an empty array, then immediately overwrote it with the value in value. Here you essentially just assigned value to the property.


#3

Why would that matter?

I did the same thing in the above array and it worked:

if (prop != “tracks” && value !== “”){
collection[id][prop] = value;
}


#4

With array.push, you are adding in new values to the array each time. By simply setting the index in the array equal to that value, you are overwriting previous values. So, if the function were to run through 3 times, adding in a different album track each time, your function would end with the track list only listing the last updated track. With push, you end up with all three tracks in the single array.

I can’t remember what was going on in this challenge exactly, but hopefully the plain-language explanation helps. If not, maybe a more pseudo - code-y type explanation might?

This is what would happen with your original code:

function updateRecords(id, prop, value) { //runs 1st time with values “1234,” “Track,” and "Song1"
collection[id][prop] = Song1

function updateRecords(id, prop, value) { //runs 2nd time with values “1234,” “Track,” and "Song2"
collection[id][prop] = Song2

function updateRecords(id, prop, value) { //runs 3rd time with values “1234,” “Track,” and "Song3"
collection[id][prop] = Song3

Whereas when you changed to array.push…

function updateRecords(id, prop, value) { //runs 1st time with values “1234,” “Track,” and "Song1"
collection[id][prop] = [Song1]

function updateRecords(id, prop, value) { //runs 2nd time with values “1234,” “Track,” and "Song2"
collection[id][prop] = [Song1, Song2]

function updateRecords(id, prop, value) { //runs 3rd time with values “1234,” “Track,” and "Song3"
collection[id][prop] = [Song1, Song2, Song3]

So, this wasn’t a very exact explanation, but hopefully I was able to get the general idea across. Best of luck on the rest of the challenges.


#5

Thank-you, that clears it up!! :slight_smile: