I wanna write a function that receive two parameter that first one is an array and the second is an integer; So I wanna return two element of the array that their sum be equal the second function's parameter. For example in this case findSum([1,2,3,5], 5) my function will return 2 and 3 that their sum being 5. I wrote a function but I think it can be better with another optimized coding.
function findSum(arr, sum){
for(element of arr) {
const first_element = element;
for(innerElement of arr){
if((innerElement !== first_element) && (innerElement + element === sum) )
return {first_element, innerElement}
}
}
}
So, one clear issue with your code is that findSum([2,2,3],4) won't work, because of this line: if((innerElement !== first_element). You should check indexes, rather than values to avoid this.
Very quick example:
findSum = (arr, sum) => {
return arr.map((x, i) => {
return arr.map((y, j) => {
if(i === j) return null;
return x + y === sum ? {x, y} : null;
}).filter(x => x);
}).flat()[0];
}
Essentially, what I''m doing is very similar to your original version, with some slight tweaks.
Rather than using two for loops like you, I use two maps to iterate over the array. This gives me access to the index (i & j).
If i === j then it's the exact same element (and not just the same value) so we can ignore it. This solves the if((innerElement !== first_element)
issue.
Then I check to see if the sum is correct and return the values, or null if it's incorrect. Filtering this array with filter(x => x) returns only the truthy elements, i.e. removes the nulls so we are left with all the matches.
We then flatten the array and return the first object as that's all we need, but we could change that to return all the matches. findSum([2,2,1,3], 4) has two matches for example.
Key concepts: Array.map Array.filter Array.flat