But is this true? Calling arr.sort() actually sorts the array in place, does it not? The variable sortedArr is initialized but never used–the original arr is used instead.
What I’m driving at is the sortedArr variable is extraneous and doesn’t need to be declared.
Can someone tell me how ineffective / effective my recursive solution is:
function sumAll(arr) {
var min = Math.min(arr[0], arr[1]),
max = Math.max(arr[0], arr[1]);
if (min === max)
return (min);
return max + sumAll([min, max - 1]);
}
sumAll([1, 4]);
And generally, how can one measure code efficiency in js ?
I also thought the reduce method should be used. I agree the code examples here without it are simpler hence a good practice. But it was fun learning more about the reduce method:
function sumAll(arr) {
var newArr = [];
newArr[0] = Math.min(…arr);
var i = Math.min(…arr);
var j=0;
var max = arr.reduce(function(a, b) {
return Math.max(a, b);
});
var min = arr.reduce(function(a, b) {
return Math.min(a, b);
});
var temp = 0;
for(var i = min; i < max + 1; i++) {
temp += i;
console.log(temp);
}
return temp;
function sumAll(arr) {
//sort array so lowest comes first
arr.sort(function(a,b){
return b < a;
});
//create sum variable and assyign total sum of arr to it
var sum = arr.reduce(function(acc, num){
return acc + num;
});
//check if we need to add the sum of number between first and last element of an array
if(arr[0] !== arr[1]){
//create second array to store numbers between first and last element of an array
var arr2 = [];
var index = arr[0]+1;//set the index
while(index < arr[1]){
arr2.push(index);//add between numbers to arr2
index++;
}
//assyign sum of arr to sum of arr2
sum += arr2.reduce(function(acc, num){
return acc + num;
});
}
return sum;
}
//test
sumAll([1, 4]);
Here I am my code using the .sort method and a for loop.
function sumAll(arr) {
var sumArr = 0, sortArr = arr.sort(function(a,b){
return a - b;
});
for(var i = sortArr[0]; i < sortArr[1]; i += 2){
sumArr += i + (i + 1);
}
return sumArr;
}
But sincerely , if the suggestion to using reduce() is for learning then solution should include it. Remember its a leanring environment . As one who teaches at a university I cannot give my students a hint then not use it. It causes confusion and frustrates learners.
function sumAll(arr) {
var max = arr.reduce(function(a, b) {
return Math.max(a, b);
});
var min = arr.reduce(function(a, b) {
return Math.min(a, b);
});
var result = 0;
for (i = min; i <= max; i++){
result += i;
}
return result;
}
A solution without using Math.max() and Math.min()
function sumAll(arr) {
var max;
var min;
var result = 0;
if (arr[0] > arr[1]) {
max = arr[0];
min = arr[1];
} else {
max = arr[1];
min = arr[0];
}
while (min <= max) {
result = result + min;
min++;
}
return result;
}