Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tripdog
Last active June 17, 2021 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tripdog/bf9f32927bba886167c547e70c42f270 to your computer and use it in GitHub Desktop.
Save tripdog/bf9f32927bba886167c547e70c42f270 to your computer and use it in GitHub Desktop.
Take the last two numbers from an array, sum them, and append to the end of the array.

Take the last two numbers from an array, sum them, and append to the end of the array.

function appendSum(nums) {
    nums.push(nums[nums.length - 1] + nums[nums.length - 2]); 
    nums.push(nums[nums.length - 1] + nums[nums.length - 2]); 
    nums.push(nums[nums.length - 1] + nums[nums.length - 2]);
    return nums
}
console.log(appendSum([1, 1, 2]))

A less elegant solution, but a solution nonetheless

function appendSum(nums) {
  let newList = nums;
  for (let i = 0; i < 3; i++) {
  let num1 = nums[nums.length - 1];
  let num2 = nums[nums.length - 2];
  newList.push(num1 + num2);
  }
   return newList;
 }
 console.log(appendSum([1, 1, 2]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment