I need to check for duplicate values in an array element. Within my array, I have multiple objects like {S:1,R:2,V:3}. My goal is to display an alert message if there are duplicate values for the "S" element in that array.
My Approach:
var arr=[{S:1,R:2,V:3},{S:2,R:2,V:3},{S:1,R:4,V:5},{S:3,R:2,V:3},
{S:2,R:2,V:3},{S:3,R:4,V:5}];
function findDuplicate()
{
var sorted_arr = arr.slice().sort();
var results = [];
for (var i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1].S == sorted_arr[i].S) {
results.push(sorted_arr[i]);
break;
}
}
console.log(results);
return results;
}
if(findDuplicate().length==1)
{
alert("S -" + findDuplicate()[0].S +" is a duplicate");
}
However, the code snippet above (referencing this answer) is not yielding the desired outcome. I am expecting an alert message stating S - 1 is a duplicate
.