我有以下数组:
var fruits = ["orange","orange,apple","apple,orange,pear"];
我正在努力实现以下目标:
fruits = ["orange","apple","pear"]
任何建议,谢谢!
我有以下数组:
var fruits = ["orange","orange,apple","apple,orange,pear"];
我正在努力实现以下目标:
fruits = ["orange","apple","pear"]
任何建议,谢谢!
没有现成的方法来实现这一点。
你可以做的是使用像字典一样的关联数组。遍历列表,读取每个元素,将其拆分并将其存储在关联数组中,其中键作为水果名称,值也作为水果名称。就像是:
fruits["orange"] = "orange";
如果该值已经存在于 fruits[] 中,它将被简单地覆盖。最后,您将在 fruits[] 中拥有与独特水果一样多的键。
编辑:
var fruits = ["orange", "orange,apple", "apple,orange,pear"];
var a = fruits.toString().split(",");
var obj = new Object();
for (var i = 0; i < a.length; i++) {
obj[a[i]] = a[i];
}
for (var key in obj) {
alert(key);
}
会给你预期的结果。
var fruits = ["orange","orange,apple","apple,orange,pear"];
var uniqueVal = [];
$.each(fruits, function(i, el){
var splitVals = el.split(',');
for(var i=0; i<splitVals.length; i++ ){
if($.inArray(splitVals[i], uniqueVal) === -1) uniqueVal.push(splitVals[i]);
}
});
尝试这个
var fruits = ["orange","orange,apple","apple,orange,pear"];
如果要拆分第二个元素并连接字符串
fruits.concat(fruits[1].split(","))
或者您希望所有元素拆分并连接然后 uniq
var new_fruits = [];
$.each(fruits, function(i, el){
fruits.concat(fruits[i].split(","))
if($.inArray(el, new_fruits) === -1) new_fruits.push(el);
});
_.uniq(fruits, false)
这应该有效:
var fruits = ["orange","orange,apple","apple,orange,pear"];
var out = [];
$(fruits).each(function(i) {
var s = fruits[i].split(',');
$(s).each(function(i) {
if($.inArray(s[i], out)===-1)
{
out.push(s[i]);
}
});
});
JSFIddle:http: //jsfiddle.net/rRC65/
这使用一个对象来捕获元素,然后返回它的键。并且不需要垫片。
function remdupes(arr) {
var obj = {}, out = [];
for (var i = 0, l = arr.length; i < l; i++) {
var el = arr[i].split(',');
for (var ii = 0, ll = el.length; ii < ll; ii++) {
obj[el[i]] = true;
}
}
for (var key in obj) { out.push(key); }
return out;
}
请注意最后几行:
for (var key in obj) { out.push(key); };
return out
可以重写:
return Object.keys(obj);
你可以这样做(消除重复):
fruits = fruits.join(','); // "orange,orange,apple,apple,orange,pear"
fruits = fruits.split(','); // ["orange", "orange", "apple", "apple", "orange", "pear"]
fruits = eliminateDuplicates(fruits); // ["orange", "apple", "pear"]