Where do I belong exercise - request feedback (not help)

Hi all,

As I move through the exercises, I am trying to pay more attention to observations about processing time and efficient code. After I finished my solution I saw that many others chose to skip the sort, so I feel happy about realizing that.

I am mainly curious whether my use of reduce is considered code abuse or if it is an acceptable use of that function?

Thank you!


function getIndexToIns(arr, num) {
  return arr.reduce(function(x,y){
    if (y<num) return x+=1;
    else return x;
  },0);
}

getIndexToIns([40, 60], 50);

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

1 Like

Oops - thank you for the heads-up!

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

As far as your use of reduce vs. sorting before hand, your solution would be more efficient which is why I like your solution. You can shorten it more with the ternary operator and using ES6 arrow function syntax (see below). I renamed your reduce arguments to make the code more readable.

const getIndexToIns = (arr, num) => arr
  .reduce((finalIdx, val) => val < num ? ++finalIdx : finalIdx, 0);
1 Like

Fascinating! Thanks for introducing me to arrow notation for functions, @RandellDawson. I also see your point about clarity in variable names.

Sorry about the spoiler tags! Thanks for fixing and pointing that out to me.