Considere la matriz [1,2,2]
La matriz contiene dos valores únicos: 1, 2
La matriz contiene valores duplicados: 2
El entero solitario es 1
¿Cómo se puede devolver el entero solitario?
Demostración de trabajo:
// 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] 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);Para una matriz en la que solo le importa tomar el primer entero que es solitario, puede verificar si indexOf y lastIndexOf son iguales. Si lo son, entonces es solitario.
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));Si tiene una matriz que tiene múltiples valores solitarios, puede usar este método para encontrar todos los valores solitarios:
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]