javascript - 在javascript中将sort和uniq函数合并为1
问题描述
我有sortBy
anduniqBy
函数,但我在组合中对数组进行了两次迭代sortUniqBy
。 这是一个代码框,这里是代码:
export const sortBy = <T>(o: T[], selector: (item: T) => any): T[] => {
const result = o.slice(0);
result.sort((x, y) => {
const a = selector(x);
const b = selector(y);
return a > b ? 1 : a < b ? -1 : 0;
});
return result;
};
export const uniqBy = <T>(o: T[], selector: (item: T) => any): T[] => {
const ret: T[] = [];
const set = new Set<T>();
o.forEach((s) => {
const value = selector(s);
if (set.has(value) === false) {
set.add(value);
ret.push(s);
}
});
return ret;
};
export const sortedUniqBy = <T>(o: T[], selector: (item: T) => any): T[] => {
return uniqBy(sortBy(o, selector), selector);
};
sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); // [1.1, 2.3]
是否可以在一个循环中以某种方式排序和删除重复项而不是两次?
解决方案
您可能会误用一个对象作为哈希表,它会像键一样按顺序对索引进行排序并从中返回值。
function sortedUniqBy(array, callback) {
const items = {};
for (const value of array) {
const temp = callback(value);
if (!(temp in items) || items[temp] > value) items[temp] = value;
}
return Object.values(items);
}
console.log(sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor)); // [1.1, 2.3]
推荐阅读
- javascript - 使用 Vue 路由器导航时防止刷新索引页面
- firebase - FirebaseError:分析:Firebase 配置中的“measurementId”字段为空
- mysql - 如何将以下 SQL 查询转换为 Laravel 查询?
- python-3.x - Python 3.8:使用 del 后类对象数据仍然存在
- javascript - 为什么 console.log 显示错误属性?
- flutter - Flutter:如何运行一个后台任务来监听数据队列?
- django - 如何将 TimeField 模型与当前时间进行比较?
- jenkins - 詹金斯从 cli 创建工作
- javascript - html2canvas 的问题
- tomcat - Debian 端口开放配置有什么问题?