Friday, December 26, 2014

An exercise from Eloquent JS

At the moment, I am at Chapter 5 of Eloquent Javascript. It's been a little while since I started slowly going through it, and recently I've decided to accelerate my reading. Attending Women Who Code JS study groups has helped quite a bit as well.

Previously, I was working through some Angular.js tutorials, yet it is definitely helpful to have a more solid understanding of Javascript fundamentals. Thanks to this resource, there are many more books to read, and I definitely feel that I need to work through several before I will feel comfortable with JS functions.

There are several exercises at the end of each chapter of Eloquent Javascript, and I am including a solution to the first one from Chapter 5. The exercise states: "Use the reduce method in combination with the concat method to "flatten" an array of arrays into a single array that has all the elements of the input arrays".

Chapter 5 provides a sample reduce function, however, I have slightly modified it. The final solution is as follows:

var arrays = [[1,2,3], [4,5], [6]];

function reduce(array, combine){
    var current = [];
    for (var i = 0; i < array.length; i++){
        current = combine(current,array[i]);
    }
    return current;
}

console.log(reduce(arrays, function(a, b){
    return a.concat(b);
}));

No comments :

Post a Comment