5

I'm trying to switch in general to functional programming and want to use underscore for JavaScript.

But I'm stuck at first base. I could not create an array at all and resorted to imperative language, and I can't seem to transform them properly either: n.length is correct, but n[0].length is undefined (see fiddle)

var a = new Array(5);
for (i = 0; i < a.length; i++) {
    a[i] = new Array(6);
}
var n = _.map(a, function (row, rowIdx) {
    _.map(row, function(col, colIdx) {
        return rowIdx * colIdx
    });
});

console.log(a.length)
console.log(n.length)
console.log(a[0].length);
console.log(n[0].length);
3
  • What exactly are you trying to do? Create a multiplication matrix? Commented Dec 17, 2013 at 17:33
  • No, I plan to put other things in the matrix but I just used this as a simple way to explain what I wanted to do Commented Dec 17, 2013 at 17:56
  • Someone added a comment that I needed to add return before the second _.map ut they deleted it afterwards. I want to record that wisdom here Commented Dec 17, 2013 at 17:56

3 Answers 3

3

To "functionally" create a 5 x 6 matrix using underscore, you could do something like this:

var matrix = _.range(5).map(function (i) {
    return _.range(6).map(function (j) {
        return j * i;
    });
});

The _.range function (documentation) is a shorthand for creating arrays that are filled with sequential numbers. For example, _.range(5) returns the array [0,1,2,3,4]. Ranges start at zero.

If you didn't want to use _.range, you could do this with raw JavaScript by using array literals:

var matrix = [0,1,2,3,4].map(function (i) {
    return [0,1,2,3,4,5].map(function (j) {
        return j * i;
    });
});
Sign up to request clarification or add additional context in comments.

Comments

3

Another way to create a matrix would be to use _.times:

var matrix = _.times(6, function(x){
    return _.times(7, function(y){

        // do whatever needs to be done to calculate the value at x,y

        return x + ',' + y;
    });
}); 

Comments

0

In ES6/2015

var range = num => Array.apply(null, Array(num)).map((i, n) => n);

var matrix2d = (a1, a2) => a1.map(i => a2.map(j => [i, j]));

console.log(matrix2d(range(5), range(6)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.