我在javascript中有一个字符串,其中有很多重复项。例如,我有:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
如何删除重复项并获取x="Int32,Double"
?
答案 0 :(得分:16)
使用Set
和Array.from
这非常简单:
Array.from(new Set(x.split(','))).toString()
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
x = Array.from(new Set(x.split(','))).toString();
document.write(x);
答案 1 :(得分:1)
如果您必须支持当前的浏览器,则可以拆分数组然后对其进行过滤
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
var arr = x.split(',');
x = arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
}).join(',');
document.body.innerHTML = x;
答案 2 :(得分:1)
这是一种更具可读性和参数化的解决方案:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
var removeDup = [...new Set(x.split(","))].join(",");
//结果为“ Int32,Double”
答案 3 :(得分:1)
签出-
removeDuplicates ()函数将字符串作为参数,然后字符串拆分函数是一个内置函数,将其拆分为单个个字符的数组。然后 arr2 数组开始时为空,一个 forEach 循环检查 arr2 中的每个元素-如果 arr2 具有元素,它将不会在其中推送字符,否则它将推送。因此,最终返回的数组包含唯一元素。。最后,我们使用 join()方法将数组连接起来,使其成为 string 。>
const removeDuplicates = (str) => {
const arr = str.split("");
const arr2 = [];
arr.forEach((el, i) => {
if (!arr2.includes(el)) {
arr2.push(el);
}
});
return arr2.join("").replace(",", "").replace("", " ");
};
console.log(removeDuplicates( "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"));
答案 4 :(得分:1)
它很简单,只需使用 new Set
和 join
删除字符串中的重复项。
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
console.log([...new Set(x)].join(""));
答案 5 :(得分:0)
function removeDuplicate(x)
{
var a = x.split(',');
var x2 = [];
for (var i in a)
if(x2.indexOf(a[i]) == -1) x2.push(a[i])
return x2.join(',');
}
答案 6 :(得分:0)
function removeDups(s) {
let charArray = s.split("");
for (let i = 0; i < charArray.length; i++) {
for (let j = i + 1; j < charArray.length; j++)
if (charArray[i] == charArray[j]) {
charArray.splice(j, 1);
j--;
}
}
return charArray.join("");
}
console.log(removeDups("Int32,Int32,Int32,InInt32,Int32,Double,Double,Double"));
答案 7 :(得分:0)
使用新的js语法从字符串中删除Dupicate。
String.prototype.removeDuplicate = Function() {
const set = new Set(this.split(','))
return [...set].join(',')
}
x.removeDuplicate()
答案 8 :(得分:0)
function myFunction(str) {
var result = "";
var freq = {};
for(i=0;i<str.length;i++){
let char = str[i];
if(freq[char]) {
freq[char]++;
} else {
freq[char] =1
result = result+char;
}
}
return result;
}
答案 9 :(得分:-1)
const str = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
const usingSpread = [...str]
const duplicatesRemove = [...new Set(usingSpread)]
const string = duplicatesRemove.join("")
console.log("After removing duplicates: " + string)
步骤