简体   繁体   中英

Math operation with two different length arrays in javascript

I have 2 arrays with different sizes like this :

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

I would like to do this :

for (i = 0; i < array1.length; i++) {
    console.log(array1[i] / array2[i]);
}

What can I do to get back at the beginning of array2 when array1.length > array2.length ?

In order to have : 1/2 - 2/2 - 3/3 - 4/1 - 5/2 - 6-3

I tried to put 2 loops but it doesn't work.

Use modulo to wrap around:

for(i=0; i< array1.length ; i++){
    console.log(array1[i] / array2[i % array2.length]);
}

You can use modulus operator to round the index of array. Modulus % will return the remainder after division, so using anyNumber % arrLen will always be less than arrLen .

 var array1 = [1, 2, 3, 4, 5, 6]; var array2 = [1, 2, 3]; var firstArrLen = array1.length, secondArrayLen = array2.length; for (i = 0; i < Math.max(firstArrLen, secondArrayLen); i++) { document.write('<pre>' + (array1[i % firstArrLen] / array2[i % secondArrayLen]) + '</pre>'); } 

Other solutions do the job well. I can propose using map for the first array to make the code look nice:

var result = array1.map(function(e, i) {
    return e + '/' + array2[i % array2.length];
});

console.log( result );  // ["1/1", "2/2", "3/3", "4/1", "5/2", "6/3"]

Replace string '/' with / (dividing operator) to get the actual values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM