筛选出仅具有唯一值的数组 [英] Filter out array to have only unique values

查看:87
本文介绍了筛选出仅具有唯一值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to filter out my array to contain only unique values. this is my array data

["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"]

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

How should i continue my code to get proper result.

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

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

If you need any additional information's please let me know and i will provide. thank you

推荐答案

您可以使用

You can use Array.filter function to filter out elements of an array based on the return value of a callback function. The callback function runs for every element of the original array.

这里的回调函数的逻辑是,如果当前项的indexOf值与索引相同,则意味着该元素是首次遇到的,因此可以认为是唯一的.如果不是,则表示该元素已经被遇到,因此应立即将其丢弃.

The logic for the callback function here is that if the indexOf value for current item is same as the index, it means the element has been encountered first time, so it can be considered unique. If not, it means the element has been encountered already, so should be discarded now.

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)中运行时具有非常大的数组.

Caveat: As pointed out by rob in the comments, this method should be avoided with very large arrays as it runs in O(N^2).

更新(2017年11月16日)

如果您可以依赖 ES6功能,则可以使用

If you can rely on ES6 features, then you can use Set object and Spread operator to create a unique array from a given array, as already specified in @Travis Heeter's answer below:

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

这篇关于筛选出仅具有唯一值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆