Skip to content

Instantly share code, notes, and snippets.

@bourroush
Created February 4, 2016 14:37
Show Gist options
  • Save bourroush/31a327aa26197c0443d3 to your computer and use it in GitHub Desktop.
Save bourroush/31a327aa26197c0443d3 to your computer and use it in GitHub Desktop.
Write a function that takes an array of numbers and returns the sum of each number multiplied by its position in the array.
// The final total as a global variable
var total = 0;
// This function will take an element and its index as param.
// We are just declaring the function here
function logArrayElements(element, index) {
// multipliying the index and element value
value = index * element;
// This console.log is just to see exactly what's happening in the console
console.log("index: "+index + " * value: " + element + " = " + value);
// After each call of the function, I'm adding the current value to the grand total
total += value;
}
// Calling the function !
[1, 2, 3, 4].forEach(logArrayElements);
// And grand total is...
console.log("Grand total : " + total);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment