We are required to write a JavaScript function that takes in one such array and counts the sum of all distinct elements of the array.
For example: Suppose, we have an array of numbers like this −
const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1];
The output for the array mentioned above will be 20.
Example
Following is the code −
const arr = [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1]; const distinctSum = arr => { let res = 0; for(let i = 0; i < arr.length; i++){ if(i === arr.lastIndexOf(arr[i])){ res += arr[i]; }; continue; }; return res; }; console.log(distinctSum(arr));
Output
Following is the output in the console −
30