Hi all,
This is a question I’ve been practicing on to get better at JavaScript. The question entails finding out how many numbers in the array (nums) is smaller than each given item of the array (returning the answer in an array of equal size).
I solved it with a nested loop (one for cycling through each item and one for comparing each item to each other item), a score keeper variable (to count how many items it’s bigger than) and an if statement to compare the values of the items in turn.
The given numbers in the array are [8, 1, 2, 2, 3] and the expected array answer for these numbers is [4,0,1,1,3] .
8 is bigger than 4 other numbers
1 is bigger than 0 other numbers, etc.
Someone else posted the below answer, which looks really good and I’d like to get my head around the functions and acrobatics they used. I’d really appreciate some help deciphering that return line!
var nums = [8, 1, 2, 2, 3];
var smallerNumbersThanCurrent = function(nums) {
return nums.map((n, i) => nums.reduce((a, c) => a + (nums[i] > c), 0))
};
console.log(smallerNumbersThanCurrent(nums))
This is what I (think!) I’ve figured out:

the array nums is mapped: each of its items (n) and the next item (is i the next item of the array to which n is compared? in the description of map it should be the index of the item) is passed to a reducing function (arrow notation).

the reducing function they’re passed to is going to return a single item. It first passes the two numbers to another function (to compare their sizes?).

the other function adds the first value to the array item at index i, if that item plus the first value is bigger than the second item. What exactly is going on here? i.e. what does that bit of code do in plain language? I’m also not sure what function and parameter the 0 refers to.
I think the next step in understanding what’s going on here is to change the arrow notation to fully expanded functions, but it’s doing my head in trying to tease out the variables and what they’re referring to exactly.
This post is getting a bit long, so I’ll leave it at that for now. Any push in the right direction would be appreciated, thanks!
This is where the original question is posted:
https://leetcode.com/problems/howmanynumbersaresmallerthanthecurrentnumber/