Javascript sum of distinct numbers!

Hello FCC campers, i need to get the sum of distinct numbers, any help ? that’s my code !


let arr1 = [2, 7, 5, 3, 4];
let arr2 = [3, 7, 5, 1, 9];
let totArr = 0;

  
for(let i = 0; i < arr1.length; i++){
  for(let j=0; j < arr2.length; j++){
    if(arr1[i] !== arr2[j] && arr2[j] !== arr1[i]){
      totArr += arr1[i] + arr2[j];
    }
  }
}

console.log(totArr)

Is this a FCC challenge? If so, could you give the link?

Ah no, it’s not an FCC challenge, just an exercise that am trying to do !

Like, add up all unique numbers from both arrays? So don’t add the 7 and the 3 twice?

No, what i have to do is the sum of unique numbers what i mean in the example above it’s 2 + 4 + 1 + 9

Hello~!

I would try approaching this in the following two steps:

  1. Create a new array that contains the unique values. I would loop through each array separately, use indexOf to see if the element is in the other array, and if it is not, put it in the new array.
  2. Get the sum of elements in the new array. I’d approach this with reduce.
1 Like

Thank you for your time and your answer, i should use it as another solution, but the thing is that i need to do it with the for loop :sweat_smile:

The same approach could be accomplished with for loops. Things like reduce can often be replicated with a standard for loop, though it’s a bit messier. :slight_smile:

1 Like

You might try using Array.includes().

2 Likes

Thank you for your answers guys, i will try and let you know :smiley:

My solution :

let arr1 = [2, 7, 5, 3, 4];
let arr2 = [3, 7, 5, 1, 9];
let totArr1 = 0;
let arr = arr1.concat(arr2);
let totArr2 = 0;

for(let i = 0; i < arr1.length; i++){
  for(let j=0; j < arr2.length; j++){
    if(arr1[i] == arr2[j]){
      totArr1 += arr1[i] + arr2[j];
    }
  }
}
  
for(let i = 0;i < arr.length; i++){
  totArr2 = totArr2 + arr[i]
}

const totArr = totArr2 - totArr1;

console.log(totArr);

To get distinct values from 2 arrays you could combine them in a single set, then convert back to an array and sum using reduce() method:

let distinctValues = new Set([...arr1, ...arr2]);
console.log([...distinctValues].reduce((a, b) => a + b));
1 Like