Home > Software engineering >  Finding the lonely integer - JavaScript
Finding the lonely integer - JavaScript

Time:02-16

Consider the array [1,2,2]

The array contains two unique values: 1, 2

The array contains duplicate values: 2

The lonely integer is 1

How can the lonely integer be returned?

CodePudding user response:

Working Demo :

// Array with duplicates
const arrWithDuplicates = [1, 2, 2];
 
var result = arrWithDuplicates.sort().filter((x,i,arr) => x !== arr[i 1] && x !== arr[i-1]);
console.log(result); // [1]

CodePudding user response:

For an array where you only care about grabbing the first integer which is lonely, you can check if the indexOf and lastIndexOf are the same. If they are, then it's lonely.

const array = [2, 2, 1, 3, 4, 3, 4];

const findLonely = (arr) => {
    for (const num of arr) {
        if (arr.indexOf(num) === arr.lastIndexOf(num)) return num;
    }
    return 'No lonely integers.';
};

console.log(findLonely(array));

If you have an array that has multiple lonely values, you can use this method to find all of the lonely values:

const array = [2, 2, 1, 3, 4, 3, 4, 6, 8, 8, 9];

const findAllLonely = (arr) => {
    const map = {};

    arr.forEach((num) => {
        // Keep track of the number of time each number appears in the array
        if (!map[num]) return (map[num] = 1);
        map[num]  ;
    });

    // Filter through and only keep the values that have 1 instance
    return Object.keys(map).filter((key) => {
        return map[key] === 1;
    });
};

console.log(findAllLonely(array)); // expect [1, 6, 9]

  • Related