Javascript 过滤出数组以仅具有唯一值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38206915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:11:19  来源:igfitidea点击:

Filter out array to have only unique values

javascriptarrays

提问by Valor_

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

expected result should be

预期结果应该是

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

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

回答by Mohit Bhardwaj

You can use Array.filterfunction 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.

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

The logic for the callback function here is that if the indexOfvalue 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.

这里回调函数的逻辑是,如果indexOf当前 item的value 与 index 相同,则表示该元素已第一次遇到,因此可以认为它是唯一的。如果没有,则表示已经遇到该元素,因此应立即丢弃。

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 );

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

警告:正如rob在评论中指出的那样,当它在O(N^2).

UPDATE (16 Nov 2017)

更新(2017 年 11 月 16 日)

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

如果您可以依赖ES6 features,那么您可以使用Set objectSpread 运算符从给定数组创建一个唯一数组,如下面的@Travis Heeter 的回答中已经指定:

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

回答by Travis Heeter

As of June 15, 2015 you may use Set()to create a unique array:

自 2015 年 6 月 15 日起,您可以Set()用来创建唯一数组:

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


For your Example:

对于您的示例:

var 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"]
var newArray = [...new Set(data)]
console.log(newArray)

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

回答by JSON C11

Filtering an array to contain unique values can be achieved using the JavaScript Setand Array.frommethod, as shown below:

可以使用 JavaScript SetArray.from方法过滤数组以包含唯一值,如下所示:

Array.from(new Set(arrayOfNonUniqueValues));

Array.from(new Set(arrayOfNonUniqueValues));

Set

The Set object lets you store unique values of any type, whether primitive values or object references.

Return valueA new Set object.

Set 对象允许您存储任何类型的唯一值,无论是原始值还是对象引用。

返回值一个新的 Set 对象。

Array.from()

Array.from()

The Array.from() method creates a new Array instance from an array-like or iterable object.

Return valueA new Array instance.

Array.from() 方法从类数组或可迭代对象创建一个新的 Array 实例。

返回值一个新的 Array 实例。

Example Code:

示例代码:

const array = ["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"]

const uniqueArray = Array.from(new Set(array));

console.log("uniqueArray: ", uniqueArray);

回答by Nina Scholz

You could use a hash table for look up and filter all not included values.

您可以使用哈希表来查找和过滤所有未包含的值。

var 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"],
    unique = data.filter(function (a) {
        return !this[a] && (this[a] = true);
    }, Object.create(null));

console.log(unique);

回答by Jesse Dirisu

arr = ["I", "do", "love", "JavaScript", "and", "I", "also", "do", "love", "Java"];

uniqueArr = [... new Set(arr)];

// or

reallyUniqueArr = arr.filter((item, pos, ar) => ar.indexOf(item) === pos)

console.log(`${uniqueArr}\n${reallyUniqueArr}`)

回答by Morteza Tourani

You can use Mapand Spread Operator:

您可以使用MapSpread 运算符

var rawData = ["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 unique = new Map();
rawData.forEach(d => unique.set(d, d));
var uniqueItems = [...unique.keys()];

console.log(uniqueItems);

回答by Zuhair Taha

Array.prototype.unique = function () {
  return [...new Set(this)]
}

then we can write:

然后我们可以写:

const arr = [1, 5, 2, 2, 2, 3, 4, 3, 2, 1, 5]
const uniqueArr = arr.unique()

回答by SovietFrontier

This is for es2015and above as far as I know. There are 'cleaner' options with ES6but this a great way to do it (with TypeScript).

es2015据我所知,这是为了及以上。有“更清洁”的选项,ES6但这是一个很好的方法(使用TypeScript)。

let values: any[] = [];
const distinct = (value: any, index: any, self: any) => {
    return self.indexOf(value) === index;
};
values = values.filter(distinct);

回答by Jose Hermosilla Rodrigo

You can use reduceto loop the array and get the not duplicate values. Also uses an aux objectto get the count of added values.

您可以使用reduce循环数组并获取不重复的值。还使用 auxobject来获取附加值的计数。

var aux = {};

var newArray = ["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"].reduce((tot, curr)=>{
  if(!aux[curr]){
    aux[curr] = 1;
    tot.push(curr);
  }
  return tot;
}, []);

console.log(newArray);

回答by omikes

A slight variation on the indexOfmethod, if you need to filter multiple arrays:

indexOf如果您需要过滤多个数组,则该方法略有变化:

function unique(item, index, array) {
    return array.indexOf(item) == index;
}

Use as such:

像这样使用:

arr.filter(unique);