Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda