Mik*_*erm 1 javascript arrays filter indexof
考虑数组 [1,2,2]
该数组包含两个唯一值:1、2
该数组包含重复值:2
孤独整数是1
如何返回孤独的整数?
对于您只关心获取第一个整数的数组,您可以检查indexOf和lastIndexOf是否相同。如果是的话,那就太孤独了。
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));Run Code Online (Sandbox Code Playgroud)
如果您有一个包含多个孤独值的数组,则可以使用此方法查找所有孤独值:
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]Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)