首页 > 解决方案 > 在javascript中将sort和uniq函数合并为1

问题描述

我有sortByanduniqBy函数,但我在组合中对数组进行了两次迭代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]

是否可以在一个循环中以某种方式排序和删除重复项而不是两次?

标签: javascripttypescript

解决方案


您可能会误用一个对象作为哈希表,它会像键一样按顺序对索引进行排序并从中返回值。

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]


推荐阅读