Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, how do I check if an array has duplicate multiple values?

I'm sorry I can't speak English well.

These are my simple code with a few parameters array:

 if (link.indexOf({"x" : "1" ,  "y":"2" ,  "z": "3"}) === -1) {
    link.push({
        "x": "1",
        "y": "2",
        "z": "3"
    });    
} else {
    alert("Duplicate");
}

Used in "for" loop but not alert Duplicate.

like image 534
Mersad Nilchy Avatar asked May 18 '26 15:05

Mersad Nilchy


1 Answers

You can create a separate function for this to check if element exists in list or not.

Try this:

function doesExistInList(list, obj) {
  for (let i = 0; i < list.length; i++) {
    if (list[i].x === obj.x && list[i].y === obj.y && list[i].z === obj.z) {
      return true;
    }
  }
  return false;
}

let link = [];
let obj = { "x": "1", "y": "2", "z": "3" };
if (doesExistInList(link, obj) == false) {
  link.push(obj);//insert same object to list
} else {
  alert("Duplicate");
}
console.log(link);
like image 151
Saurabh Agrawal Avatar answered May 21 '26 06:05

Saurabh Agrawal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!