Reduce Method
What was your “wow” moment when you started coding? I know there probably are many and all have a great story attached to them but for me it was when I got introduced to the reduce method. As far as I could remember I had not used it both in real work environment and or on my own for something. So when I got to see it in action it seemed almost like magic to me. It was such a weird thing to see, hard to grasp for what it was being used at that moment but I really enjoyed the “mystery” of it.
You could build arrays and objects out of it and manipulate data from it to be any shape or form you wanted. It seems like you could do anything and everything with it. Of course now I know you shouldn’t rely on one single method to do everything you want but at that time it just captivated me and I dove into it to get to know how to properly use it.
The MDN docs suggest only using it for mostly summing an array, promise sequencing and function piping. Although I do think you can use it for far more than just that, we always gotta follow best procedures for the work environment we are in and or work regulations / pr reviews.
Having said that I recently came across a very simple use of the reduce method I would like to share here which reminded me that it still is by far my favorite javascript method to date, weather its nostalgia or not… well that’s something I can think about later on.
const array = [1, 3, 3 , 2 , 2];
// 1 = 01 -> value
// 2 = 10 -> value
// 3 = 11 -> value
// 1 ^ 3 = 01 - 11 -> 10 = 2
// 2 ^ 3 = 10 - 11 -> 01 = 1
// 1 ^ 2 = 01 - 10 -> 11 = 3
// 3 ^ 2 = 11 - 10 -> 01 = 1
function lonelyInteger(arr) {
return arr.reduce((acc, curr) => acc ^ curr);
}