lundi 10 juin 2019

Javascript - Arrays - for-loop to forEach

Given an array of integers where every value appears twice except one, find the single, non-repeating value.

Follow up: do so with O(1) space.

1) How to solve?

2) Is forEach pretty much the same as a for-loop?

How could this be rewritten with a forEach?

This is not giving me the output I'd like, which for this example, should just return 4

CODE

 const nonRepeat = arr => {
 
     let newArray = [];

     for (let i = 0; i < arr.length; i++) {
 
       for (let j = 0; j < arr.length; j++) {

         if (arr[i] !== arr[j]) {

           newArray.push(arr[i])

         }
        }
       }
     return newArray
    }

console.log(nonRepeat([2, 5, 3, 2, 1, 3, 4, 5, 1]));

Aucun commentaire:

Enregistrer un commentaire