I have a few arrays in array :
([[10,0],[3,5],[5,8]])
I try substract all inner arrays a - b and then sum results ( example : 10 - 0 = 10, 3-5 = -2, 5-8 = -3, 10+(-2)+(-3) = 5;
My try:
var el;
return array.reduce((a, b) => a - b );
But my result came out Nan, now Im understood, in my code i want substring array from array - bad idea. I know how do this with using for
or something like that, my question is:
how i can do this with use reduce
or other ''modern'' method?
Thanks for help.
PS sorry for my English skill ;)
You can use reduce()
method like this.
var data = [[10,0],[3,5],[5,8]] var result = data.reduce((r, e) => r + (e[0] - e[1]), 0); console.log(result)
Flexible solution, the size of the nested arrays doesn't matter, it will still return a proper result.
const count = (arr) => arr.reduce((s, v) => { s += v.reduce((a,b) => a - b); return s; }, 0); let arr1 = [ [10, 0], [3, 5], [5, 8] ], arr2 = [ [5, 4, 1], [3, 5, 5], [5, 8] ]; console.log(count(arr1)); console.log(count(arr2));
Something like this? You were close, but be sure to have an initial value of 0
and dereference the inner arrays into a
and b
like so:
var array = [[10,0],[3,5],[5,8]]; var result = array.reduce((prev, [a, b]) => prev + (a - b), 0); console.log(result);
const arr = ([[10,8],[3,5],[5,8]]);
arr.map(pair => pair[0] - pair[1]).reduce((a,b) => a + b)
You could reduce the outer and inner arrays.
var array = [[10, 0], [3, 5], [5, 8]], result = array.reduce(function (r, a) { return r + a.reduce(function (x, y) { return x - y; }) }, 0); 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.