Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
Finding the lonely integer - JavaScript

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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]

about 4 years ago · Juan Pablo Isaza Report

0

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

let lonely = array.filter((item,index)=> array.indexOf(item) === array.lastIndexOf(item));
console.log(lonely);

about 4 years ago · Juan Pablo Isaza Report

0

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]

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!