voi*_*oid 31 javascript arrays string jquery unique
我试图通过广度优先搜索获得邻居列表(具体来说:Block'd中相同颜色的邻居球的索引)我function getWholeList(ballid)
返回一个像
thelist=["ball_1","ball_13","ball_23","ball_1"]
Run Code Online (Sandbox Code Playgroud)
当然还有重复.
我试图用jQuery.unique()删除它们; 但是我觉得它不能用于字符串,所以有没有办法(使数组唯一)?
谢谢你的帮助..
Guf*_*ffa 68
jQuery unique
方法仅适用于DOM元素数组.
您可以使用each
和inArray
方法轻松创建自己的uniqe函数:
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/Guffa/Askwb/
Koo*_*Inc 10
作为非jquery解决方案,您可以使用如下的Arrays filter
方法:
var thelist=["ball_1","ball_13","ball_23","ball_1"],
thelistunique = thelist.filter(
function(a){if (!this[a]) {this[a] = 1; return a;}},
{}
);
//=> thelistunique = ["ball_1", "ball_13", "ball_23"]
Run Code Online (Sandbox Code Playgroud)
作为扩展Array.prototype
(使用缩短的filter
回调)
Array.prototype.uniq = function(){
return this.filter(
function(a){return !this[a] ? this[a] = true : false;}, {}
);
}
thelistUnique = thelist.uniq(); //=> ["ball_1", "ball_13", "ball_23"]
Run Code Online (Sandbox Code Playgroud)
[ 编辑2017 ] ES6对此的看法可能是:
Array.from(["ball_1","ball_13","ball_23","ball_1"]
.reduce( (a, b) => a.set(b, b) , new Map()))
.map( v => v[1] );
Run Code Online (Sandbox Code Playgroud)
试试这个 - Array.unique()
Array.prototype.unique =
function() {
var a = [];
var l = this.length;
for(var i=0; i<l; i++) {
for(var j=i+1; j<l; j++) {
// If this[i] is found later in the array
if (this[i] === this[j])
j = ++i;
}
a.push(this[i]);
}
return a;
};
thelist=["ball_1","ball_13","ball_23","ball_1"]
thelist=thelist.unique()
Run Code Online (Sandbox Code Playgroud)
这里有 PHParray_unique
函数的 JavaScript 端口: http: //phpjs.org/functions/array_unique
function array_unique (inputArr) {
var key = '',
tmp_arr2 = {},
val = '';
var __array_search = function (needle, haystack) {
var fkey = '';
for (fkey in haystack) {
if (haystack.hasOwnProperty(fkey)) {
if ((haystack[fkey] + '') === (needle + '')) {
return fkey;
}
}
}
return false;
};
for (key in inputArr) {
if (inputArr.hasOwnProperty(key)) {
val = inputArr[key];
if (false === __array_search(val, tmp_arr2)) {
tmp_arr2[key] = val;
}
}
}
return tmp_arr2;
}
Run Code Online (Sandbox Code Playgroud)
或者从后来的 JS 开始:
arr.filter((v, p) => arr.indexOf(v) == p)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
86751 次 |
最近记录: |