aviate wong
aviate wong

Reputation: 813

modulus algorithm going through an array

I expect the result to be 3,1,0,0 but it gave me 3,1,1,1 instead. Anything wrong with my algorithm below using modulus?

points = [6,5,4,2];
var arr = [];
points.forEach(function (obj, i) {
    var a = 21;
    a = a % points[i] || "";

    arr.push(a);

});

console.log(arr);

http://jsfiddle.net/ufegq7kp/

Upvotes: 1

Views: 429

Answers (3)

Jaykumar Patel
Jaykumar Patel

Reputation: 27604

forEach prototype take two argument element, index. So you can use element value for the every iteration.

View: jsFiddle

index - The index of the current element being processed in the array.

element - actual element value of current element.

points = [6,5,4,2];
var arr = [];
points.forEach(function (element, index) {
    var a = 21;
    a = a % element || "";
    arr.push(a);

});

console.log(arr);

JavaScript forEach Doc

Upvotes: -1

dting
dting

Reputation: 39287

In [1]: 21 % 6
Out[1]: 3

In [2]: 21 % 5
Out[2]: 1

In [3]: 21 % 4
Out[3]: 1

In [4]: 21 % 2
Out[4]: 1

Your output is the expected output.

Unrelated: Instead of looking up the value by index from points, you already have the value in your forEach function as obj:

var points = [6,5,4,2],
    arr = [];

points.forEach(function (obj) {
    var a = 21;
    a = a % obj || "";
    arr.push(a);
});

console.log(arr);

Upvotes: 5

Thalsan
Thalsan

Reputation: 5690

The modulus returns the remainder of the divide.

21 / 6 = 3 (remainder 3)
       21 % 6 = 3
21 / 5 = 4 (remainder 1)
       21 % 5 = 1
21 / 4 = 5 (remainder 1)
       21 % 4 = 1
21 / 2 = 10 (remainder 1)
       21 % 2 = 1

There is nothing wrong with your modulus or the way you use it. The result you are expecting is wrong.

Upvotes: 1

Related Questions