53.0k views
2 votes
Function _one(array)

Create a JavaScript function that meets the following requirements:




Please give your function a descriptive name
o ( _one is not acceptable, and is only displayed here for illustration purposes)
Receives an array of integers as an argument
The function removes all duplicates (if they exist) from the array and returns it to the caller.
Assume the input array parameter will have at least one element in it.
Examples :
_one([33])
➔ [33]
_one([33, 33, 1, 4])
➔ [1, 4]
_one([33, 33, 1, 4, 1]) ➔ [4]​

User Neverlord
by
4.0k points

1 Answer

2 votes

Answer:

function removeRepeaters(list){

var goodList = [], badList = {}, used = {}, n;

// ensure that the argument is indeed an array

if(!Array.isArray(list)){

throw "removeRepeaters: Expecting one argument of type Array";

}

// loop through the array and take note of any duplicates

for(n in list) used[list[n]] == true ? badList[list[n]] = true : used[list[n]] = true;

// now loop through again, and assemble a list of non-duplicates

for(n in list) if(badList[list[n]] == undefined) goodList[] = list[n];

return goodList;

}

Step-by-step explanation:

I assume you're familiar with trinary operators, but just in case, that's what's happening in this first for loop:

for(n in list) used[list[n]] == true ? badList[list[n]] = true : used[list[n]] = true;

this is the same as saying:

for(n in list){

if(used[list[n]] == true){

badList[list[n]] = true;

} else {

used[list[n]] = true;

}

}

This loop flags all of the values in the list that are duplicated. Note that both "badList" and "used" are declared as objects instead of arrays. This allows us to compare keys in them with an == operator, even if they're not defined, making it a convenient way to flag things.

Note that I haven't tested it, so I may have overlooked something. I suggest testing it before handing it in.

User Martin Atkins
by
4.2k points