js
输入: [1, 1, 1, 2, 2, 3, 3, 4, 5, 1];
输出: [1, 2, 3, 4, 5];
输入: [1, 1, 1];
输出: [1];
js
function myUniq(arr) {
// Create an empty object to keep track of unique elements
const uniqueElements = {};
// Iterate through the array and add elements to the object
for (const element of arr) {
uniqueElements[element] = true;
}
// Create a new array from the object's keys (which are the unique elements)
const resultArray = Object.keys(uniqueElements).map(Number);
return resultArray;
}
module.exports = myUniq;
- 遍历与记录
js
for (const element of arr) {
uniqueElements[element] = true;
}
假设输入是 [1, 2, 1]:
遇到第一个 1:对象变成 { "1": true }
遇到 2:对象变成 { "1": true, "2": true }
遇到第二个 1:对象依然是 { "1": true, "2": true }(重复的键被覆盖了)
- 类型转换
js
const resultArray = Object.keys(uniqueElements).map(Number);
- Object.keys(uniqueElements): 这个方法会提取对象中所有的键名,返回一个字符串数组,
例如 ["1", "2"]。 - .map(Number): 因为对象的键名永远是字符串,而题目要求处理的是数字数组,所以需要通过 .map(Number) 将字符串 ["1", "2"] 转回数字 [1, 2]。
这种方法的逻辑是:"先把数字存成对象的标签(自动去重),再把标签撕下来转回数字。"