[英]How can i remove the duplicated elements in my array?
我使用了這段代碼,但我只能刪除下一個和前一個,如果它相等
for (let i = 0; i < this.userlist.length; i++) {
if (this.userlist[i] == this.userlist[i+1])
this.userlist.splice(i+1, 1);
if (this.userlist[i-1] == this.userlist[i+1])
this.userlist.splice(i+1, 1);
}
如何刪除所有重復的元素?
編輯 n°1
data() {
return {
formlogin: "",
userID: "Guest",
logged: false,
userlist: []
};
},
mounted() {
this.userID = localStorage.getItem("userID");
if (this.userID != "Guest") this.logged = localStorage.getItem("logged");
if (localStorage.userlist)
this.userlist = JSON.parse(localStorage.getItem("userlist"));
},
props: {},
methods: {
login: function() {
if (this.formlogin != "") {
this.userID = this.formlogin;
this.formlogin = "";
this.logged = true;
localStorage.setItem("logged", this.logged);
localStorage.setItem("userID", this.userID);
this.userlist.push(this.userID);
for (let i = 0; i < this.userlist.length; i++) {
if (this.userlist[i] == this.userlist[i + 1])
this.userlist.splice(i + 1, 1);
if (this.userlist[i - 1] == this.userlist[i + 1])
this.userlist.splice(i + 1, 1);
}
localStorage.setItem("userlist", JSON.stringify(this.userlist));
console.log("data sent :", this.userID, this.logged);
alert("Welcome : " + this.userID);
} else alert("cant login with a null username");
},
這就是我的用戶列表將如何更新。
帶有Set()
的es6
擴展運算符
var items = [4,5,4,6,3,4,5,2,23,1,4,4,4]; console.log([...new Set(items)]);
或,
var items = [4,5,4,6,3,4,5,2,23,1,4,4,4]; console.log(Array.from(new Set(items)));
使用filter
方法
var items = [4,5,4,6,3,4,5,2,23,1,4,4,4]; var newItems = items.filter((item, i) => items.indexOf(item) === i); console.log(newItems);
使用reduce
方法
var items = [4,5,4,6,3,4,5,2,23,1,4,4,4]; var newItems = items.reduce((uniq, item) => uniq.includes(item)? uniq: [...uniq, item], []); console.log(newItems);
你幾乎明白了!
for (let i = 0; i < this.userlist.length; i++) {
if (this.userlist[i] == this.userlist[i+1]){
this.userlist.splice(i+1, 1);
i--;
}
}
在您的解決方案中,最多刪除兩個元素。 您可以做的是刪除下一個元素並確保索引不會增加(因此i--
,因此在下一次迭代中if
將再次檢查相同的索引)。
然而,這僅適用於排序列表。 檢查 solanki 的答案以獲得更通用的答案。
使用reduce
你可以做這樣的事情。 檢查當前索引是否與data
中找到的第一個索引相同
var data = ["user", "user", "user", "foo", "foo"] var res = data.reduce((acc, elem, idx, arr)=> (arr.indexOf(elem) === idx? [...acc, elem]: acc),[]); console.log(res)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.