0

Please let me know is this a best approach to find unique number from an array?

var singleNumber = function(nums) {
  for (var i = 0; i < nums.length; i++) {
    if (i === 0) {
      nums[0] = 0 ^ nums[0];
      /* console.log(nums[0]); */
    } else {
      nums[0] ^= nums[i];
      /* console.log(nums[0]); */
    }

  }
  console.log(nums[0]);
  return nums[0];


};

singleNumber([2, 2, 3, 3, 4]);

If you have any better approach with this, help me out.

6
  • 2
    Possible duplicate of Get all unique values in an array (remove duplicates) Commented May 10, 2018 at 1:29
  • 2
    Maybe this question has to be on Code Review Commented May 10, 2018 at 1:31
  • It returns 5 with input [2, 2, 3, 1, 3, 4] and 2 for [2, 2, 3, 1, 3, 3]maybe there's a better method. Commented May 10, 2018 at 1:36
  • singleNumber([2,2,3,3,4,5]) = 1, is that what you want? Commented May 10, 2018 at 1:37
  • @icecub did you check the above question carefully? It is not duplicate. Commented May 10, 2018 at 2:44

1 Answer 1

2

I've created two functions that return unique numbers from a passed array:

var getFirstUniqueNumber = function(nums) {
    var number = null;
    var map = {};
    nums.forEach((val) => {
        if (!map[val] && (number === null)) number = val;
        if (map[val] && (number !== null)) number = null;
        map[val] = true;
    });
    return number;
};

var getLastUniqueNumber = function(nums) {
    var number = null;
    var map = {};
    nums.forEach((val) => {
        if (!map[val]) number = val;
        map[val] = true;
    });
    return number;
};

I've created a Fiddle here: https://jsfiddle.net/u88qgxrr/2/

They do what the name says, you probably want the last unique number!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.