1

I got to solve this like this:

function repeatedNumbers2(a, b) {
    for (let i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) {
        console.log(a[i], b[i]);
        }
    }
}

repeatedNumbers2(arr1, arr2);

Then I try to put it inside an array:

function repeatedNumbers(a, b) {
    for (let i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) {
            let newArr = [];
            newArr.push(a[i]);
            newArr.push(b[i]);
            return newArr;
        }
    }
}

console.log(repeatedNumbers(arr1, arr2));

Already found this better solution, but just wanna know whymy second try didn't work.

function newArray(a, b) {
    console.log([
        ...a.filter((x) => !b.includes(x)),
        ...b.filter((x) => !a.includes(x)),
    ]);
}

newArray(arr1, arr2);
Gaspar
  • 52
  • 6
  • you have created instance inside if condition and return the value once if condition is getting true. This will not process all the records. – Hermenpreet Singh Jul 16 '20 at 17:17

2 Answers2

0

Your second solution does not work because you defined your array inside the if block. Define it before the for loop and it will work fine. For further information about the issue, see https://www.w3schools.com/js/js_scope.asp

Wael Ben Zid El Guebsi
  • 2,670
  • 1
  • 17
  • 15
0

Your should define your array at the top of the function and only return at the end so you don't exit the first time you find two elements that aren't equal.

function repeatedNumbers(a, b) {
    let newArr = [];
    for (let i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) {
            newArr.push(a[i]);
            newArr.push(b[i]);
        }
    }
    return newArr;
}

function repeatedNumbers(a, b) {
    let newArr = [];
    for (let i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) {
            newArr.push(a[i]);
            newArr.push(b[i]);
        }
    }
    return newArr;
}
console.log(repeatedNumbers([1,2,3],[1,4,5]));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80