I have a list of array in this format
data = [[1,2,3,4,5,6,7,8,9,10],
[11,12,13,14,15,16,17,18,19,20],
[21,22,23,24,25,26,27,28,29,30]]
I want the output in this format
[[11/1, 12/2,13/3,14/4,15/5,16/6,17/7,18/8,19/9,20/10],
[21/11,22/12,23/13,24/14,25/15,26/16,27/17,28/18,29/19,30/20]]
I have used for loop and this is how it looks
const totalData = data.length;
for(var i =0 ; i < totalData ; i++){
for(var j =0; j < data[i].length; j++){
console.log(data[i+1][j]/data[i][j]);
}
}
I want to convert this using javascript map and reduce? is there any possible ways? Thank you
for
loops aren't bad practice, they just don't fit in a functional style of programming. The following solution presupposes that the arrays' lengths are equal:
const data = [ [1,2,3,4,5,6,7,8,9,10], [11,12,13,14,15,16,17,18,19,20], [21,22,23,24,25,26,27,28,29,30] ]; const result = data.map((arr, index) => { const next = data[index + 1]; if (!Array.isArray(next)) { return; } return arr.map((item, i) => next[i] / item); }).filter(Boolean); console.log(result);
I am sure you can figure out what to do if the arrays' lengths are not equal.
You could use a single reduce and map the items for a new array.
var data = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]], result = []; data.reduce((a, b) => (result.push(a.map((c, i) => b[i] / c)), b)); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You need to create separated functions for each task:
/**
* Combine 2 arrays
* @param Array a
* @param Array b
*/
function combineArrays(a, b) {
var combined = [];
for (var i = 0; i < a.length; i++)
combined.push(a[i] / b[i]);
return combined;
}
/**
* Combine an group of arrays
* @param Array group
*/
function combineGroup(group) {
var newGroup = [];
for (var i = 0; i < group.length - 1; i++)
newGroup.push(combineArrays(group[i], group[i + 1]));
return newGroup;
}
The first function combine 2 arrays only. The second function combine many arrays and return what you want.
if the lengths are not equal, the items in the tail of the longer one are ignored.
data = [
[1,2,3,4,5,6,7,8,9,10],
[11,12,13,14,15,16,17,18,19,20],
[21,22,23,24,25,26,27,28,29,30]
];
result = data.reduce((acc,current,i)=>{
var ret;
if(data[i].length <= data[i-1].length)
ret = data[i].map((item,j)=>(item / data[i-1][j]));
else
ret = data[i-1].map((item,j)=>(data[i][j] / item));
if(i==1)
return [ret]
else
return acc.concat([ret])
})
console.log(result)
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.