Brie Brie - 25 days ago 14
jQuery Question

Is there a way to store the items that are removed from jQuery.uniqueSort() in a variable?

I have the following jQuery script:

var greetingsArray = [
"Hello, Debbie!",
"Hello, Randy!",
"Hello, Carl!" ,
"Hello, Patrick!",
"Hello, Susan!",
"Hello, Susan!",
"Hello, Carl!"
];

$.uniqueSort(greetingsArray);


Is it possible to get the items that were removed from the array? If so, how would it be used to display a message showing these values?

For example, I have the following HTML:

<div id="greetings"></div>


I want to display removed duplicate greetings in that div element with the following jQuery script:

var greetingsRemoved = ...;
$("#id").html("Removed the following duplicate greetings: " + greetingsRemoved);


What can I put in place of ... to make that happen? I hope this is neither too difficult nor complicated.

Answer

Although it is probably a bad thing to use jQuery.uniqueSort() for doing this because of the reason stated in its description within the API Documentation, for some reason, it works as intended as follows:

var greetingsArray = [
    "Hello, Debbie!",
    "Hello, Randy!",
    "Hello, Carl!" ,
    "Hello, Patrick!",
    "Hello, Susan!",
    "Hello, Susan!",
    "Hello, Carl!"
];

var sortedArray = greetingsArray.slice().sort();
var greetingsDuplicate = [];

for (var i = 0; i < greetingsArray.length - 1; i++) {
	if (sortedArray[i + 1] == sortedArray[i]) {
		greetingsDuplicate.push(sortedArray[i]);
	}
}

alert("Duplicate Greetings: " + greetingsDuplicate.join(", "));

$.uniqueSort(greetingsArray);

alert("Greetings: " + greetingsArray.sort().join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

However, there is a better way to do this by implementing the methods derived from both answers provided here and here instead to more accurately display the results you desire.

    var greetingsArray = [
        "Hello, Debbie!",
        "Hello, Randy!",
        "Hello, Carl!" ,
        "Hello, Patrick!",
        "Hello, Susan!",
        "Hello, Susan!",
        "Hello, Carl!"
    ];
    
    var greetingsUnique = [];
    
    $.each(greetingsArray, function(index, value){
        if($.inArray(value, greetingsUnique) === -1) greetingsUnique.push(value);
    });
    
    alert("Unique: " + greetingsUnique.sort().join(", "));
    
    var sortedArray = greetingsArray.slice().sort();
    var greetingsDuplicate = [];
    
    for (var i = 0; i < greetingsArray.length - 1; i++) {
    	if (sortedArray[i + 1] == sortedArray[i]) {
    		greetingsDuplicate.push(sortedArray[i]);
    	}
    }
    
    alert("Duplicate: " + greetingsDuplicate.join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Comments