Search code examples
javascriptarraysloopscontinue

JavaScript Arrays delete duplicate words or characters(if only characters are entered. Not to delete from 1 word all duplicates


Enter : Samsung , Enter again : Samsung , Enter again: Tomas, Enter again: sass, Enter again : sass, Enter again: b, Enter again : b, Enter again : bb, Enter again : bb........

And to display the following : With removeDuplicateUsingSet: Samsung, Tomas, sass, b, bb Without the function : Samsung,Samsung,Tomas,sass,sass,b,b,bb,bb and the loop to stop when you type stop.....

function removeDuplicateUsingSet(arr){
let unique_array = Array.from(new Set(arr))
return unique_array}

var inputs =[];
var alreadyEntered = false;
while (!alreadyEntered) 
{
var input = prompt("Enter items until you enter it twice");

for (var i=0;i<inputs.length;i++) {
    if (inputs[i] == input)
     {
        alert("Already entered!");
        alreadyEntered = true;
        break;
    }

}
inputs.push(input);
}



alert("With removeDuplicateUsingSet function : " + "\n" + 
removeDuplicateUsingSet(inputs) + "\n" + "Without: " + "\n" + inputs);

Now this code have break loop and i don't know how to fix it.... Tried doing this next thing :

function removeDuplicateUsingSet(arr){
let unique_array = Array.from(new Set(arr))
return unique_array
}

var array = [];
var stored = [];
while(array !== 'stop')
{
stored.push(prompt('what are your fav books ? '));
array = prompt('If you would like to continue enter any key otherwise enter or type stop');

// document.write(stored + " , ");
console.log(removeDuplicateUsingSet(array) + "\n___________");
}
alert("With removeDuplicateUsingSet function : " + "\n" + 
removeDuplicateUsingSet(array) + "\n" + "Without: " + "\n" + stored);

but also not what i have been wanted.... It keeps removing all of the duplicate characters (ex. "Samsung" displays it SAMUNG,where i want to remove if there are entered 2 same elements(items) Please help me. Thanks in advance.


Solution

  • Is this your desired output?

    function removeDuplicateUsingSet(arr) {
      let unique_array = Array.from(new Set(arr))
      return unique_array
    }
    
    var inputs = [];
    while (true) {
      var input = prompt("Enter items until you enter it twice");
      if (input == 'stop') break;
    
      inputs.push(input);
    }
    
    alert("With removeDuplicateUsingSet function : " + "\n" + removeDuplicateUsingSet(inputs) +
      "\n" + "Without: " + "\n" + inputs);