Hello Guys,
Just wanted to ask a question regarding this topic. On my first method i have an array of numbers and I’m looping/iterate the array of numbers., then grab the two smallest numbers and add them, to return their adding value of the two values. (This works well.)
Now. I wanted to do this with new sort() and splice() Methods ES6 syntax, but i wanted to check with you guys if my method 2 its another way of accomplish this. and if I’m doing it right for best practices.
I have attach code pen just in case somone need to do testing or work on the code adjustments.
https://codepen.io/ivanmt07/pen/MWeMBXx?editors=1012
Can you let me know , i appreciate this. Kind Regards.
Method 1: Good old vanilla js with for loop.
var dogQWalks = [19, 5, 42, 2, 77];
dogQWalks.sort(function(a, b) {
return a - b;
});
for( var i = 0; i < dogQWalks.length; i= i + 1 ){
var total = 0;
total = total + dogQWalks[i];
}
const sumTwoSmallestNumbers = (numbers) => {
//Code here
let ordered = numbers.sort(function(a,b){return a-b;});
// console.log(ordered);
let result = 0;
for (let i = 0; i < ordered.length; i++){
if (i===0){
result = result + ordered[0]; //2
console.log(result);
}
if (i===1){
result = result + ordered[1]; //5
console.log(result);
}
}
return result;
};
console.log(sumTwoSmallestNumbers([19, 5, 42, 2, 77]));
//Output: (2 + 5) = 7
Method 2: Using sort() and Splice () Method.
function addLowerNum(dogQWalks){
var orderNumbers = dogQWalks.sort(function(a, b) {
return a - b;
});
//console.log(orderNumbers);
var loweNumbers = orderNumbers.splice(0,2);
//console.log(loweNumbers);
var total = 0;
for( var i = 0; i < loweNumbers.length; i++ ){
total = total + loweNumbers[i];
}
return total;
//console.log(total);
};
console.log(addLowerNum([19, 5, 42, 2, 77]));
//Output: (2 + 5) = 7