JSFiddle - React, Tailwind, and code Playground
JavaScript
/* Given an array of integers [3, 5, 2, 8, 1, 9], create a new array where each element is the sum of the current element and the next element in the original array. If there is no next element, the new array should contain the current element. */
var arr = [3, 5, 2, 8, 1, 9]
function addElements(arr){
let newarr = []
for(let i=0; i<arr.length; i++){
if(arr[i]!=arr[arr.length-1]){
newarr.push(arr[i]+arr[i+1])
}else{
newarr.push(arr[arr.length-1])
}
}
return newarr
}
console.log(addElements(arr))