gpt4 book ai didi

javascript - 是否有一种非循环每个单个列表项的方法来查找唯一的列表项?

转载 作者:行者123 更新时间:2023-11-28 01:07:45 25 4
gpt4 key购买 nike

我知道我可以使用循环每个单列表项方法来过滤掉给定列表中的唯一元素,但我觉得可能有一种简洁、快速的方法来做到这一点。

如何在 JavaScript 中找到唯一的列表项,而不需要手动循环和过滤它们?

最近我正在研究事件处理补丁,并且需要快速方法来过滤掉必须经常运行的回调列表中的唯一函数处理程序。

这就是我正在尝试做的事情:

  Array.prototype.unique = (function () {

// main Array#unique method
var uni = function uni () {
return this.filter(uni.x);
};

// attach a helper for resolving unique elements
// if element is at current position, not before,
// it's unique one, pass `true` flag to .filter()
uni.x = function (node, pos, ls) {
return pos === ls.indexOf(node);
};

// save
return uniq;
})();

实现:

// sample list:
// generate ~1K long list of integers:
// get the keys of string object of length 32,
// map every item to key-list itself,
// flatten, shuffle..
var ls =
Array.prototype.concat.apply([],
Object.keys(new String('1'.repeat(32)))).
map(function (node, pos, list) { return list; }).
sort(function () { return Math.random() < Math.random(); });

// run each function 1K times fetching unique values
for (

var
it = -1,
l = 1000,

// record iteration start
tm = Date.now();

++it < l;

ls.unique()

);

最佳答案

没有。如果您有一个列表,则需要对每个项目至少查看一次,以确定它是否是唯一的。

如果您需要更快的速度,请不要使用列表。

顺便说一句,即使在列表上,您也可以用小于当前拥有的 O(n²) 的时间实现一个独特算法。请参阅Easiest way to find duplicate values in a JavaScript array一些聪明的方法。

I was working on event handling patch and needed fast method for filtering out unique function handlers in a callback list which got to be run quite frequently.

那么您一开始就不想将它们放入该列表中。运行时不要检查列表中的重复项(正如您所说,这很常见),而是在插入新处理程序时检查。

如果您认为使用 .indexOf 在列表中查找处理程序仍然太慢,您可以将每个函数对象标记为已包含在列表中。选择一个唯一的(每个列表)属性名称,并为列表中每个函数的该属性设置一个值。然后,您可以在恒定运行时间中检查重复项。

关于javascript - 是否有一种非循环每个单个列表项的方法来查找唯一的列表项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24876612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com