Using reduce in Javascript to sum both empty and non empty arrays - javascript

I am trying to find a way to write a function that sums up all the elements within an array. I have been trying to implement this using JavaScripts reduce function. The problem I am having is that i want this function to work on both an empty array and an array with elements as separate scenarios. The following example passes the test case for an empty array but then not when the array has elements and vice versa.
function sum (numbers) {
numbers = ['a', 'b', 'c'];
return numbers.reduce(function (x, y, i) {
return x + y + i;
}), 0 };
I was looking at the signature of the reduce function and trying to implement this on the basis of that but something seems to be missing in my knowledge here.
function (previousValue, currentElement, currentIndex, array)

the following works with both an array of numbers, and an empty array (where the result will obviously be zero)
var sum = numbers.reduce(function(prev,curr){
return curr + prev;
},0);
Below is a demo of both your scenarios
function sum(numbers){
var x = numbers.reduce(function(prev,curr){
return curr + prev;
},0);
return x;
}
alert(sum([1,2,3]));
alert(sum([]));

Related

how to obtain values from forEach javascript

I've always used array.forEach(element=>console.log(element) to see what I am obtaining from array; but now I want to obtain the values themselves.
Suppose I have the following code:
array=['1','2','3','4']
array.forEach(x=>x)//undefined
What I want to obtain is :
'1'
'2'
'3'
'4'
is this the correct approach or there is some other way I am not seeing right now?
array.forEach() presents each value to your callback one at a time. That's how it works and to use that, you put code into the callback that does something with the values.
As an example:
let array = [1,2,3,4];
let product = 1;
array.forEach(x => {
console.log(x);
// update the product variable
product *= x;
});
console.log(product);
If you're trying to do array.forEach(x, ...) in the console, then you see undefined because array.forEach() has no return value (and thus undefined).
Other array functions such a .map(), .filter(), .reduce(), etc... all have return values, and you can pick one of them depending upon what type of operation you're trying to do on the array.
For example, the previous code block, could have been written with .reduce()
let array = [1,2,3,4];
let product = array.reduce((total, x) => {
console.log(x);
return total * x;
}, 1);
console.log(product);
And, here's an example of .map() that returns a new array with every value squared:
let array = [1,2,3,4];
let product = array.map(x => {
return x ** 2;
}, 1);
console.log(product);

How to sum elements of two multidimensional arrays?

I have 2 multidimensional arrays:
[[230.0], [10.0], [12.0]]
[[50.0], [60.0], [89.0]]
And am trying to sum each element together and keep the same array structure. So it should look like:
[[280.0], [70.0], [101.0]]
I tried this:
var sum = array1.map(function (num, index) {
return num + array2[index];
});
But I get this:
[23050, 1060, 1289]
Any help would be appreciated. Thanks.
The code, you use, takes only a single level, without respecting nested arrays. By taking na array with only one element without an index of the inner array and using an operator, like +, the prototype function toString is invoced and a joined string (the single element as string, without , as separator) is returned and added. The result is a string , not the result of a numerical operation with +.
You could take a recursive approach and check if the value is an array, then call the function again with the nested element.
function sum(a, b) {
return a.map((v, i) => Array.isArray(v) ? sum(v, b[i]) : v + b[i]);
}
console.log(sum([[230], [10], [12]], [[50], [60], [89]]))
Make it like this
var sum = array1.map(function (num, index) {
return parseInt(num) + parseInt(array2[index]);
});
You should have to make parseInt or parseFloat so it can convert string with them
STEPS
Iterate through every number in the array (array length).
Sum the objects of the same index in both of the arrays.
Push the sum into another array for the result. Use parseFloat if the input is string.
(Optional) use .toFixed(1) to set decimal place to have 1 digit.
const arr1 = [[230.0], [10.0], [12.0]]
const arr2 = [[50.0], [60.0], [89.0]]
let sum = []
for (let i = 0; i < arr1.length; i++){ // Assume arr1 and arr2 have the same size
let eachSum = parseFloat(arr1[i]) + parseFloat(arr2[i])
sum.push([eachSum.toFixed(1)])
}
console.log(sum)
You are trying to add two arrays structures inside the map function.
so one solution so you can see what is happening is this...
array1.map((a,i) => a[0] + array2[i][0])
screenshot from the console...
Inside map fn you should:
return parseInt(num) + parseInt(array2[index]);
This is happening because when you are trying to add them, these variable are arrays and not integers. So they are evaluated as strings and concatenated.

Use reduce function to compare symbol in the two string

I try to compare two strings in array on equal symbols or char,this code works, but how to implement it in ES6 with reduce method, if I have more than two strings an array. I need to return true if the string in the first element of the array contains all of the letters of the string in the second element of the array. But how to create the more flexible function if I have more than 2 elments in the array.
function mutation(arr) {
var arr2 = arr.map(item => item.toLowerCase().split(''));
for (i=0;i<arr2[1].length;i++) {
if (arr2[0].indexOf(arr2[1][i]) < 0)
return false;
}
return true;
}
mutation(["hello", "hey"]);
#Palaniichuk I thought your original algorithm was pretty solid. To handle your request I was able to create a solution that uses reduce.
I do have one question for you. Should the array increase in size, how would the strings be evaluated?
The reason I ask is because using a helper function like this might help you scale this algorithm. Of course it all depends on how the input changes. How the inputs are evaluated.
function makeStr(string) {
const reducer = string.split('').reduce((a, b) => {
a[b] = a[b] + 1 || 1;
return a;
}, {});
return Object.keys(reducer).sort().join('');
}
function secondMutation(arr) {
const array = [...arr].map(makeStr);
return array[0].includes(array[1]);
};
console.log(secondMutation(["hello", "hell"]));

Need to fetch the numbers from an array

I have got an array of the form:
['32 68', '56 78', '77 99']
I want to o/p another array which will contain the sum of each element in the index using JavaScript (NodeJS). Something like,
['100', '134', '176']
I tried to use .split("") but the double integer number again gets separated as separate digits. Is there any other way to solve this? Please not that, the i/p can be single digit number or double digit.
You'll want to get each item, split on a space (if exists) then add up the corresponding split. Something like this:
var origValues = ['32 68', '56 78', '77 99', '7'];
var addedValues = origValues.map(function(value) {
return value.split(' ')
.map(function(sArray) {
return parseInt(sArray);
})
.reduce(function(a, b) {
return a + b;
});
});
document.write(JSON.stringify(addedValues));
Note that this above example handles the case where you have a single digit inside your array value as well.
To provide some explanation as to what is happening...
You start off taking your original array and you are mapping a function on to each value which is what is passed into that function.
Inside that function, I am splitting the value by a space which will give me an array of (possibly) two values.
I then apply the map function again onto the array and parse each value in the array to an integer.
Last, I reduce the integer array with a summation function. Reduce applies an accumulator function to each item in the array from left to right so you will add up all your values. This result is returned all the way back up so you get your new array with your answers.
Kind of what it looks like in "drawing" form:
Start: origValues = ['32 68', '56 78', '77 99', '7']
Apply map (this will track one value): value = '32 68'
Apply the split: ['32', '68']
Map the parse integer function (I'm going to track both values): [32, 68]
Reduce: 32 + 68 = 100
I don't have time for an explanation (sorry) but, split + reduce will do it.
var arr = ['32 68', '56 78', '77 99'];
var sumArray = arr.map(function (s) {
return s.split(' ').reduce(function (a, b) {
return parseInt(a, 10) + parseInt(b);
});
});
document.write(JSON.stringify(sumArray));
You don't actually need map or anything. For each string we can .split, Numberify, and add.
secondArray[value] =
Number((firstArray[value].split(" "))[0]) +
Number((firstArray[value].split(" "))[1]);
Modifying this and turning this into a for loop, we get:
var arr2 = [];
for(var i = 0; i < arr.length; i ++){
arr2.push(
Number((arr[i].split(" "))[0]) +
Number((arr[i].split(" "))[1]));
}
arr = arr2;

Cumulative sum of array, with condition in another array

I need to perform a cumulative sum of an array. Under certain conditions, I need it to be straight forward, and found this snippet to work great:
cumul = sum.reduce(function (a, n) {
a.push((a.length > 0 ? a[a.length-1] : 0) + n);
return a;
}, [initial]);
cumul.shift();
Logger.log(cumul);
When I log 'cumul' I get the result I need. However, under other IF() conditions, I need to perform the cumulative sum providing a certain condition in another array containing dates is met - if the date is <= X, don't add to the cumulative sum in this iteration (show previous cumulative value).
Any ideas how to implement this? It seems that using this version of a cumulative sum won't work, but I'm not sure what would be other ways to go about this.
Thanks in advance!
G
You're making life far too hard on yourself with all that pushing and reducing and shifting.
function running_total(array, init) {
return array
.map(function(v, i) { return v ===3 ? 0 : v; }) // filter out 3's
.map(function(v) { return init += v; })
;
}
document.writeln(running_total([1,2,3,4,5], 0));
To make the filter pertain to another, parallel array of dates, change the first map function to something such as
function(v, i) { return dates[i] < cutoff ? 0 : v; }
For loops are very fast in Javascript, and can create all kinds
of conditional sums.
The function ccSum() below takes 2 parameters, a data array and a condition array.
The data is summed if the condition is true.
function ccSum(data, condition){
var r = [];
r[0] = (condition[0])? data[0]: 0;
for(i=1,l=data.length; i<l; ++i) r[i] = r[i-1] + ( (condition[i])? data[i]: 0 );
return r
}
It would be easy to rewrite this where condition is a function to be called, by changing the square bracket condition[i] for a round one condition(i). Alternatively, we could check typeof(condition)==='function' and branch these two cases.

Categories