-1

I have the answer in Kotlin but I need it in Javascript.

fun main() {

var sum = 0

for (i in list.indices){
    if(i == 0){
        sum = list[0].sum()
    }else if( i == list.lastIndex)
    {
        sum += list[list.lastIndex].sum()

    }else {
        sum+=list[i].first() + list[i].last()
    }
}
println(sum)

}

val list = listOf( listOf(3, 8, 9, 7, 6), listOf(6, 3, 8, 9, 7), listOf(7, 6, 3, 8, 9) )

In this exapmle the correct answer should be 79

  • So the correct approach is to calculate the sum of elements in the first and last arrays and add the sum of first and last elements in the middle arrays. Can someone write this? – Lado Gelava Jul 12 '20 at 14:03
  • Stack Overflow is not a free code conversion service. It is up to those asking to do the basic research and show their code attempts to solve their own issues. Others will be happy to help when those attempts don't work as expected – charlietfl Jul 12 '20 at 14:04
  • Does this answer your question? [Sum of numbers in an array with javascript](https://stackoverflow.com/questions/52686772/sum-of-numbers-in-an-array-with-javascript) – user120242 Jul 12 '20 at 14:08

1 Answers1

1

Working Code !!

const data = [
  [3, 8, 9, 7, 6],
  [6, 3, 8, 9, 7],
  [7, 6, 3, 8, 9]
];
let sum = 0, arrSum = 0;
data.map((ar, index) => {
  arrSum = index !== 1 ? ar.reduce((acc, curr) => acc + curr) : ar[ar.length - 1] + ar[0]
  sum += arrSum;
});
console.log(sum);
solanki...
  • 4,982
  • 2
  • 27
  • 29