DEV Community

Discussion on: Mastering Hard Parts of JavaScript: Callbacks III

Collapse
 
khushbu_thakur profile image
KHUSHBU THAKUR • Edited

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) => {
         if(callback(item)){
            sArr.push(item);
         } else {
           arr.push(item);
         }
     });
  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);
            if(a.hasOwnProperty(key)){
              a[key] = [...a[key], c];
           }else{
             a[key] = [c];
          }
        return a
    }, {})
}
Enter fullscreen mode Exit fullscreen mode

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

Collapse
 
internettradie profile image
Ryan Ameri

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! 😁

Collapse
 
jkoo92 profile image
JKoo92

Hi Khushubu thank you for your comment. I just have a quick question. I see that you use the spread operator "..." a lot. Is there a reason as to why you need to use it? I'm curious. under what circumstances do you need to use it?