'javascript to return values on decrement
My code is following
var points = 4;
var yModifier = [];
for (var i = 0; i <= points; i++) {
yModifier.push([]);
};
yModifier.forEach(
(a, j) => {
var start = j;
var end = start + points;
for (var i = start, k = 0; i <= end; i++, k++) {
yModifier[j].push([k, i])
};
}
);
console.log(yModifier);
which produces the following
0: [[0,0],[1,1],[2,2],[3,3],[4,4]]
1: [[0,1],[1,2],[2,3],[3,4],[4,5]]
2: [[0,2],[1,3],[2,4],[3,5],[4,6]]
3: [[0,3],[1,4],[2,5],[3,6],[4,7]]
4: [[0,4],[1,5],[2,6],[3,7],[4,8]]
How can I modify the forEach
to give me the following
0: [[0,0],[1,1],[2,2],[3,3],[4,4]]
1: [[0,-1],[1,0],[2,1],[3,2],[4,3]]
2: [[0,-2],[1,-1],[2,0],[3,1],[4,2]]
3: [[0,-3],[1,-2],[2,-1],[3,0],[4,1]]
4: [[0,-4],[1,-3],[2,-2],[3,-1],[4,0]]
Solution 1:[1]
var points = 4;
var yModifier = [];
for (var i = 0; i <= points; i++) {
yModifier.push([]);
};
yModifier.forEach(
(a, j) => {
var start = j; //a =0, start=0
var end = start + points; //a =1, end=360
for (var i = start, k = 0; i <= end; i++, k++) {
yModifier[j].push([k, k - j])
};
}
);
console.log(yModifier);
Solution 2:[2]
Looks like the pattern for values is [col, col - row]
:
var points = 4;
var yModifier = Array.from({ length: points + 1 }, function(_, row) {
return Array.from({ length: points + 1 }, function(_, col) {
return [col, col - row];
});
});
console.log(yModifier);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | tbjgolden |
Solution 2 | Salman A |