0

I used this code but with that i can only remove the next one and the previuous one if its equal

 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);
    }

How can i remove all the duplicated elements?

edit 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");
},

thats how my userlist will be updated.

3 Answers3

8

es6 spread operator with Set()

var items = [4,5,4,6,3,4,5,2,23,1,4,4,4];
console.log([...new Set(items)]);

OR,

var items = [4,5,4,6,3,4,5,2,23,1,4,4,4];
console.log(Array.from(new Set(items)));

Using filter method

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);

Using reduce method

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);
solanki...
  • 4,982
  • 2
  • 27
  • 29
0

You almost got it!

for (let i = 0; i < this.userlist.length; i++) {
  if (this.userlist[i] == this.userlist[i+1]){
    this.userlist.splice(i+1, 1);
    i--;
  }
}

In your solution, two elements are removed at most. What you can do instead is remove the next element an make sure that the index doesn't increase (hence the i--, so in the next iteration if will check the same index again).

This however only works for sorted lists. Check solanki's answer for a more generic one.

Felix Jassler
  • 1,029
  • 11
  • 22
0

Using reduce you can do something like this. Check if the current index is same as the first index found in 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)
ABGR
  • 4,631
  • 4
  • 27
  • 49