I have a function sum([1,2,3,4],50,10,[10, 20],1)
, consisting of both integers and arrays and I want to return the sum of all single elements. In the given example the sum would be 101.
Question: I found a way that works, but I'd like to know, what I could do to make it more efficient.
My approach works as follows:
- intialize a new array; those arguments that are arrays, like
[1,2,3,4]
, will be turned into a sum first and then pushed into the new array. - for-loop through all arguments
- check, if argument is an array
- if yes, sum all elements up (via
.reduce()
) and push sum into new array. - if no, push element into new array
- if yes, sum all elements up (via
- Turn
newArray
into sum (again via.reduce()
) and return.
Code:
console.log("Result: " + sum([1,2,3,4],50,10,[10, 20],1));
function sum(...allArgs) {
let newArray = [];
// go through all args
allArgs.forEach((elem) => {
// check if argument is an array
if (Array.isArray(elem)){
// arraySum = all Items of array
arraySum = elem.reduce((acc, currV) => acc + currV, 0);
// push arraySum into new Array
return newArray.push(arraySum);
}
// push other arguments (that are not arrays) into new array
newArray.push(elem);
});
// return the sum of the new array
return newArray.reduce((acc, currV) => acc + currV);
}
I found a comparable post, with the difference that in that post no arguments were arrays, hence this post.
What could I improve in this procedure?