我正尝试使用以下代码从数组中删除重复的值:
for (var i = 0; i < a.length; i++)
obj[a[i]] = a[i]
a = new Array();
// Removing duplicates by checking each objects with keys.
for (var key in obj)
a.push(obj[key]);
它删除重复项,但我的问题是,它还考虑了空格。
这是我的数组:
["Cardiologist", "Cardiologist", "Cardiologist ", "Neurologist ", "Neurologist "]
删除重复项后,我会变成这样
["Cardiologist", "Cardiologist ", "Neurologist "]
“心脏病专家”值由于空白而重复。我怎样才能得到我期望的确切结果?
答案 0 :(得分:2)
您可以使用string.prototype.trim()
从字符串的开头和结尾删除空格。我建议您在重复数据删除之前应用它。
myString.trim()
示例:
const arr = ["Cardiologist", "Cardiologist", "Cardiologist ", "Neurologist ", "Neurologist "];
const trimmedArr = arr.map((v) => v.trim());
console.log(trimmedArr);
运行该命令,您会看到所有前导/后缀空格都消失了。现在您可以进行比较了!