fbpx

My latest browser game is done, I have deployed it to a temporary website and will share the link to it soon. Anyway, while building it, I came across this little problem where I was trying to partition arrays. As usual, there’s more than one way to solve the problem. In fact, there are 3 ways to solve it. Let’s start with the least efficient solution.

Partition arrays

Inefficient i.e. n squared runtime. See we have to go (iterate) through all elements of the array twice.

Inefficient approach (using filter)

let correctAns = questionStack.filter(val => {
  return val.userAns === val.correctAnswer;
});
let wrongAns = questionStack.filter(val => {
  return val.userAns !== val.correctAnswer;
});

Old Fashioned (using old for loop)

Old fashioned but runs in linear time and I kinda like it.

let correctAns;
let wrongAns;
for(let i=0; i < questionStack.length; i++) {
  let curQ = questionStack[i];
  if(curQ.userAns == curQ.correctAnswer) {
    correctAns.push(curQ);
  } else {
    wrongAns.push(curQ);
  }
}

Modern (using reduce)

The one below is the by far the shortest and also the least readable in my opinion.

Array.prototype.partitionWith = function(f) {
  return this.reduce((a, x) => a[f(x)+0].push(x) && a, [[],[]])
}
var isRight = x => x.userAns === x.correctAnswer;
var [right, wrong] = questionStack.partitionWith(isRight);
console.log(right);
console.log(wrong);

However it does run in linear time i.e. partitions the array in just one pass. The unreadability aspect is just my personal opinion a lot of Javascript developers would love this approach. To me, it’s less readable and harder to debug.

Like the blog? Subscribe for updates

As usual, if you find any of my posts useful support us by  buying or even trying one of our products and leave us a review on the app store.

‎My Day To-Do - Smart Task List
‎My Day To-Do - Smart Task List
‎AUD $ Currency Converter
‎AUD $ Currency Converter
Developer: Bhuman Soni
Price: $0.99
‎My Day To-Do Lite - Task list
‎My Day To-Do Lite - Task list
‎Snap! I was there
‎Snap! I was there
Developer: Bhuman Soni
Price: Free
Numbers Game: Calculation Master
Numbers Game: Calculation Master
‎Simple 'N' Easy: Todos & food
‎Simple 'N' Easy: Todos & food
‎Captain's Personal Log
‎Captain's Personal Log
Developer: Bhuman Soni
Price: $4.99
My Simple Notes
My Simple Notes
Developer: Bhuman Soni
Price: Free
‎My Simple Notes - Dictate
‎My Simple Notes - Dictate
Developer: Bhuman Soni
Price: $2.99
Categories: Javascript

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *