考慮陣列 [1,2,2]
該陣列包含兩個唯一值:1、2
該陣列包含重復值:2
孤獨的整數是 1
如何回傳孤獨的整數?
uj5u.com熱心網友回復:
作業演示:
// 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]
uj5u.com熱心網友回復:
對于只關心獲取第一個孤立整數的陣列,您可以檢查 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));
如果您有一個包含多個孤獨值的陣列,則可以使用此方法查找所有孤獨值:
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]
uj5u.com熱心網友回復:
對于每個元素,您可以使用它.filter()來幫助計算元素重復的次數。然后.filter()再次使用以僅回傳那些出現一次的元素。
const nums = [1,2,2,3,4,4,4,5,5,6,7,7,7,8,8];
const singles = nums.filter(
//count how many times each element appears
num => nums.filter(n => n === num)
//return only those with freq. of 1
.length === 1
);
console.log( singles );
//OUTPUT: [ 1, 3, 6 ]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/425129.html
標籤:javascript 数组 筛选 指数
