I'm trying to write a map/reduce to get the average of each array within an array.
For example.
[[1][2,3][4,5,6,7]] => [1, 2.5, 5.5]
Right now this is my code where result is the array of arrays:
result.map(array => {
return array.reduce((a, b) => (a + b)) / array.length;
})
const result = [
[1],
[2, 3],
[4, 5, 6, 7]
]
console.log(result.map(array => {
return array.reduce((a, b) => (a + b)) / array.length;
}))
Any help to get the desired output is much appreciated. As it stands, my output is reducing to an array of NaN's instead of the averages.
You need a closing parentesis.
By using Array#reduce with arrays with unknown length, you need to take a start value, which is in this case of a length of zero the result.
var result = [[1], [2, 3], [4, 5, 6, 7]],
avg = result.map(array => array.reduce((a, b) => a + b, 0) / array.length);
// ^^^ ^
// optional required
console.log(avg);
you must provide a second argument to the reduce function, the initial value of a. So:
result.map(array => {
return array.reduce((a, b) => a + b, 0) / array.length;
});
You may also want to ensure that array.length > 0 before you divide by it
Related
i have a problem with reduce.
I want to add the rest of the arrays from the first array in the array.
array = [[a,b],[c,d],[e,f]]
the order to come is: (a-b)+(c-d)+(e-f), but my code not work :((
my code is:
const sumAndSubtract = (numberInNestedArray) => {
return numberInNestedArray.reduce((acc, cur, ind, arr) => {
const firstSubtract = arr[0][0] - arr[0][1];
const otherSubtract = acc[ind] - cur[ind];
console.log(firstSubtract);
console.log(otherSubtract);
return firstSubtract + otherSubtract;
})
}
console.log(sumAndSubtract([
[10, 0],
[5, 7],
[6, 9]
]))
expect result: 10 + (-2)+(-3)
Use reduce as follows, where a is the accumulating sum, and b and c are the atomic values retrieved from each pair:
let result = [[10, 0], [5, 7], [6, 9]].reduce((a, [b, c]) => a+b-c, 0);
console.log(result);
In your attempt, the following is not right:
The expression arr[0][0] - arr[0][1]. This only looks at the first pair in the array, and does so in each iteration. Instead, you should be doing cur[0] - cur[1].
The expression acc[ind] - cur[ind]: ind is the index in the outer array, which takes values 0, 1 and 2 for the example input. acc[ind] is a pair, not a number and cur[ind] will at some point be an out of range reference, as cur only has two values.
The call to reduce should get the initial value argument, because without it, the first pair will be the initial value of acc, which you don't want: you want a number. So pass 0 as initial value argument to reduce.
What you call otherSubtract is already given as acc, so you actually don't need this variable.
The shortest way to do it will be:
numberInNestedArray.reduce((acc, cur) => acc + (cur[0] - cur[1]), 0)
You could map the subtractions and add the values later.
const
add = (a, b) => a + b,
subtract = (a, b) => a - b,
sumAndSubtract = array => array
.map(a => a.reduce(subtract))
.reduce(add);
console.log(sumAndSubtract([[10, 0], [5, 7], [6, 9]]));
I would like to find out if swapping elements can be done using only .reduce in JavaScript. If not, what else should be used from the functional programming land?
This is not for sorting an array. I wanted to find all the permutations of the array element using .reduce which required the swap step as per this method.
You could take a function which takes an array and two indices and uses a destructuring assignment.
const swap = (array, i, j) => [array[i], array[j]] = [array[j], array[i]];
var array = [1, 2, 3];
swap(array, 0, 1)
console.log(array);
A version with reduce by taking an array of indices and swap all pairs from start to end.
const
swap = (array, ...indices) =>
indices.reduce((a, b) => ([array[a], array[b]] = [array[b], array[a]], b));
var array = [1, 2, 3];
swap(array, 0, 1)
console.log(array);
In es6, the idiomatic way to swap array elements is:
;[a[i], a[j]] = [a[j], a[i]]
Using .reduce is not appropriate for this task. You could technically do something like this:
a = a.reduce((acc, element, idx) => {
acc.push(idx === i ? a[j] : idx === j ? a[i] : a[idx])
return acc
}, [])
but it would result in convoluted code.
If your goal is to avoid mutating the original array, you can use Object.assign:
b = Object.assign([], a, {[i]: a[j], [j]: a[i]})
The reduce function reduces the array to a value of an object, as defined by the accumulator.
let array1 = [2, 5, 8, 0, 10];
let array2 = [1, 4, 9, 7, 6];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
The sort() method sorts the elements of an array in place and returns the array. The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
var months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const sortingAccending = (a, b) => a - b
let numbers = [4, 2, 5, 1, 3];
numbers.sort(sortingAccending);
console.log(numbers);
// expected output: Array [1, 100000, 21, 30, 4]
And you answer your question, reduce can't be used for swapping elements.
You will have to either use sort for write your custom sort function
After reading the docs on map method,I still cannot get this to work.
I am trying to use map to get the average of every pair of numbers in an array.Please help me understand whats wrong.
function getAverage(num1,num2){return Math.ceil((num1+num2)/2)};
function a(input){ var b = input.map(getAverage(num1,num2)); return b; }
a([1,2,3,4]) //error num1 is not defined
//expected [2,4]
map projects a function to each element of a list/array, it simply "maps" a function over all the items.
[1, 2, 3].map(function (number) { return number + 1; });
// -> [2, 3, 4]
Therefor, first you need to have pairs of items in your "input" array, so it looks like this:
var numberPairs = [[1, 2], [3, 4]]
Until now, all you have are just single numbers but no pairs.
After conversion, you can use map like this:
numberPairs.map(function (pair) {
return Math.ceil((pair[0] + pair[1]) / 2);
});
This will give:
[2, 4]
as a result.
You can't calculate the average using a map. A mapping pass a function to each element and then returns an array with the same shape. That is not the case, you want to get a value from an array, and you can use the reduce method for that.
// adds two number
const adder = (a,b) => a + b;
// reduces the array adding all numbers and divides
// by the array length
const getAverage = (arr) => arr.reduce(adder)/arr.length;
// outputs 2.5
console.log(getAverage([1,2,3,4]))
You can use reduce() instead of map() to aggregate averages of every n values in the array:
const sum = array => array.reduce((a, b) => a + b, 0)
const getAverage = n => (averages, value, index, array) => index % n === 0
? [...averages, Math.ceil(sum(array.slice(index, index + n)) / n)]
: averages
const result = [1, 2, 3, 4].reduce(getAverage(2), [])
console.log(result)
I have two arrays (a,b) and my task is to find the difference of their volumes i.e. i have to multiply all elements of array a, then do the same for array b and then subtract the two to find the difference.
I tried using forEach() and reduce() in conjuction with arguments but it seems that the last element of each array is left out and what I get as output is NaN.
This is my code
function findDifference(a, b) {
var args = Array.prototype.slice.call(arguments);
var results = [];
args.forEach(function(argument){
return argument.reduce(function(a,b){
results.push(a*b);
});
});
return results;
}
and this is my output for findDifference([3, 2, 5], [1, 4, 4]);
[6, NaN, 4, NaN]
Looks like the multiplication stops with the second element of each array. Any ideas?
Why not just multiply the given arrays and take the delta of the results?
function findDifference(a, b) {
return [a, b]
.map(a => a.reduce((a, b) => a * b))
.reduce((a, b) => a - b);
}
console.log(findDifference([3, 2, 5], [1, 4, 4]));
With arguments.
function findDifference(a, b) {
return Array.prototype
.map.call(arguments, a => a.reduce((a, b) => a * b))
.reduce((a, b) => a - b);
}
console.log(findDifference([3, 2, 5], [1, 4, 4]));
Instead of storing each multiplication in result array, you can store the result of all the multiplication of each array in result array.
function findDifference(a, b) {
var args = Array.prototype.slice.call(arguments);
var results = [];
args.forEach(function(argument){
results.push(argument.reduce(function(a,b){
return a*b;
}));
});
return results;
}
console.log(findDifference([3, 2, 5], [1, 4, 4]));
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);