gpt4 book ai didi

javascript - 过滤数组以具有唯一值

转载 作者:行者123 更新时间:2023-12-02 22:21:26 25 4
gpt4 key购买 nike

我需要过滤掉我的数组以仅包含唯一值。这是我的数组数据

["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"]

预期结果应该是

["X_row7", "X_row4", "X_row6", "X_row10", "X_row11", "X_row8", "X_row9"]

我应该如何继续我的代码以获得正确的结果。

newArray = [];
for(n in data){
if(!newArray.indexOf(n)){
newArray.push(n);
}
}
console.log(newArray);

如果您需要任何其他信息,请告诉我,我会提供。谢谢

最佳答案

您可以使用Array.filter函数根据回调函数的返回值过滤掉数组的元素。回调函数针对原始数组的每个元素运行。

这里回调函数的逻辑是,如果当前项的indexOf值与索引相同,则意味着该元素是第一次遇到,因此可以认为它是唯一的。如果没有,则意味着已经遇到过该元素,因此应该立即丢弃。

var arr = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"];

var filteredArray = arr.filter(function(item, pos){
return arr.indexOf(item)== pos;
});

console.log( filteredArray );

警告:正如 rob 所指出的那样在注释中,应避免使用非常大的数组,因为它的运行时间为 O(N^2)

更新(2017 年 11 月 16 日)

如果您可以信赖ES6 features ,那么您可以使用 Set objectSpread operator从给定数组创建一个唯一的数组,如下面 @Travis Heeter 的答案中所指定:

var uniqueArray = [...new Set(array)]

关于javascript - 过滤数组以具有唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38206915/

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