DEV Community


Discussion on: Mastering Hard Parts of JavaScript: Callbacks III

khushbu_thakur profile image

For Challenge 13, as given in the original question, if we were to maintain order,
Your solution will log :

['sunny', 'seinfeld', 'curb', 'rickandmorty', 'friends']

But the expected output is

['seinfeld', 'sunny', 'curb', 'rickandmorty', 'friends']

So to maintain the order following solution might work,

function prioritize(array, callback) {
    let arr = [], sArr = [];
        array.forEach((item, index) => {
         } else {
  return [...sArr, ...arr];
Enter fullscreen mode Exit fullscreen mode

For challenge 15, it's good that you have shown more use-case of the reduce method.

But it is not an optimal solution as using 2 loops make the time complexity O(N*N).
This problem can be done using a single loop too i.e. O(N).

function groupBy(array, callback) {
    return array.reduce((a,c) => {
          let key = callback(c);
              a[key] = [...a[key], c];
             a[key] = [c];
        return a
    }, {})
Enter fullscreen mode Exit fullscreen mode

Finding in an object is much efficient than finding it in an array.

internettradie profile image
Ryan Ameri Author

Thank you Khushbu for going through the challenges and providing improved solutions.

For challenge 13, as you noted, I slightly modified the original challenge as I thought it would be neater if all truthy values come first. I'll add your solution as an alternative.

For challenge 15, your solution is indeed much more performant. My goal was to use declarative array methods as much as possible. I'll include your solution as a faster alternative.

Thanks again for the feedback! 😁