My solution for "Where do I Belong?"

I wrote a blog post on how I solved “Where do I Belong?” - the JavaScript Coding Challenge.

I really hope this will be useful for the community!
If you have any questions or concerns, let me know and I’d be happy to help! :grinning:

The main disadvantage of map/filter/reduce compared to a simple for loop is the lack of early return.

And for a really “fancy” solution you should replace acc === -1 with !~acc and save additional n keystrokes (crazy golfers) :smirk:

I remember that I spent hours and hours on some coding challenges, sometimes I even spent several hours in a night just to find the solution and… oh boy, how happy I was when I finaly did it. :smiley:

I simultaneously loved and hated Advent of Code.

1 Like

I’m glad you got through the entire post! :grin:

Thanks for the addition! Didn’t know about the !~acc. Learned something knew! :+1:t2:

@Flopet17, I don’t think using .reduce() to find an index is a wise decision. This would look coolest to me:

const getIndexToIns = (arr, num) =>  [...arr, num].sort((a, b) => a - b).indexOf(num);

Remember, that you write code for people, not for a computer. And people expect reducer to return some accumulated value and not the indexOf item inside :slight_smile:

I think reduce is better thought of as returning a value that was updated for every item in the array. This distinction can be pretty important when you talk about reducing an Observable.

Observable adds ‘so far’ at the end, so value accumulated so far :slight_smile:

That is true @snigo! Good point.

I was so distracted for using reduce, I forgot that there is a simpler way! :joy: Thanks for pointing out!

After I’ve read the comments I received about my solutions I learned that there is an even “faster” way to solve the challenge. I updated the blog post with the third solution which involves only looping through the array once!

Thank you for the idea! :grinning: