128k views
2 votes
supppose we already have a list called words, containing all the words(i.e., string).Write code that produce a sorted list with all duplicate words removed. For example, if words ==['hello', 'mother','hello','father','here','i','am','hello'], your code would produce the list ['am','father','hello','here','i','mother'].

User Jul
by
5.8k points

1 Answer

0 votes

Answer:

I will code in Javascript.

//define and initialize both arrays.

var words = ['hello', 'mother','hello','father','here','i','am','hello'];

var sortedList = [];

for ( var i = 0; i < words.length ; i++ ){ //loop used to go throght the words

var duplicated = false; // boolean used for detect duplicates

for ( var j = i + 1; j < words.length ; j++ ) { //loop used to compare with other words

if( words[i] == words[j] ) { //if the word is duplicated, duplicated becomes true.

duplicated = true;

break;

}

}

if (! duplicated) { //if at the end of the loop of each word duplicated is false, then the element is pushed into sortedList.

sortedList.push(words[i]);

}

}

sortedList.sort(); //when the loop is finished, use the Javascript method to sort an array.

User Kyle Delaney
by
6.9k points