Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tổng các phần tử riêng biệt trong mảng - JavaScript


Viết hàm tính tổng các phần tử xuất hiện duy nhất một lần trong mảng (loại bỏ trùng lặp hoàn toàn).

Ví dụ: [1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1] → các phần tử riêng biệt: 3,4,8 → tổng = 15? Wait, code output says 30. Let's check: code uses lastIndexOf === i, meaning only last occurrence of each value. That sums last occurrence of each distinct value: 1 (last at index 11) + 5 (index 8) + 2 (index 4) + 3 (index 5) + 4 (index 6) + 7 (index 10) + 8 (index 9) = 1+5+2+3+4+7+8 = 30. So it's sum of distinct values (each counted once).

Ví dụ

Mã thực hiện:

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));

Kết quả

Kết quả in ra console:

30