Challenge 8 Megathread

Welcome to challenge 8! Use this thread for any and all questions relating to challenge 8.

Need some help with challenge 8? Watch this video from 21DCC coder @iamdp:

one liner :slight_smile:
const smartGarbage = (trash, bins) => Object.assign({}, bins, {[trash]: bins[trash] + 1})

3 Likes

27%20AM

Nice! Same!

const smartGarbage = (trash, bins) => {
  if (trash === "waste" || trash === "recycling" || trash === "compost"){
    bins[`${trash}`] ++;
  }
  return bins
}

Went the longer way! In case trash of some random category.

1 Like

Today it’s hard to me understand this challenge…I’m stuck :slightly_frowning_face:

const smartGarbage = (trash, bins) => {
    // Code here!
 for (trash in bins){
   if(bins.hasOwnProperty(trash)){
     var totTrash = bins[trash];
    
   }
 }
};

I did this

const smartGarbage = (trash, bins) => {
  if (bins[trash]) bins[trash]+=1;
  return bins;
}
1 Like

My code print key and value but I don’t how to increment trash

You can fix it this way:

const smartGarbage = (trash, bins) => {
  // Code here!
  for (x in bins){
    if(x == trash){
      bins[x]+=1;
    }
  }
  return bins;
};

Or you may just do this:

const smartGarbage = (trash, bins) => {
  // Code here!
  if(bins.hasOwnProperty(trash)){
    bins[trash]+=1;   
  }
  return bins;
}
3 Likes

Thanks it works!!!
I didn’t have to put the for loop … I learned a new thing :slightly_smiling_face:

1 Like

Lol when the test cases are minimum:

solution
    const smartGarbage = (trash, bins) => {
        bins[trash] += 1;
        return bins;
    }
3 Likes

this is the best solution

short and sweet

solution
const smartGarbage = (trash, bins) => ({...bins, [trash]: bins[trash]+1})

Solved:

solution

55%20AM

1 Like

bins[trash]++;
return bins;

very simple solution

3 Likes

took a slightly longer approach by using switch:

solution
const smartGarbage = (trash, bins) => {
    // Code here!
    switch(trash)
    {case "waste":
      bins.waste++
      break;
    case "recycling":
      bins.recycling++
      break;
    case "compost":
      bins.compost++;
    }
    return(bins)
}

What happens when trash is “foo”? :wink:

haha yeah I did bins[trash]++; felt like cheating.

Perfect, a lot of other solutions don’t take into account that trash could be something non-existing :wink:

Note, these are the same (because trash is a string):

bins[`${trash}`]
bins[trash]