0

I am trying to pass a function that removes duplicates from an array. It should handle strings, object, integers as well. In my code so far I am showing that it will handle strings but nothing else. How can Imake this function universalto handle numbers,handle arrays,handle objects, and mixed types?

let unique = (a) => a.filter((el, i ,self) => self.indexOf(el) ===i);

In this function I hav unique() filtering to make a new array which checks the element and index in the array to check if duplicate. Any help would be appreciated.

  • What you consider as duplicates in case of objects, for example? If you need more flexible solution go for: https://lodash.com/docs/4.17.4#uniq For strings and integers, this would be the shortest way to remove duplicates: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set – sinisake Dec 20 '17 at 00:10
  • I can't use lodash on this just pure Javascript – Demetri Bethel Dec 20 '17 at 00:26
  • Possible duplicate of [Get all unique values in an array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-an-array-remove-duplicates) – Dexygen Dec 20 '17 at 00:43

2 Answers2

0

i think the first you should do is to sort the array ( input to the function ). Sorting it makes all the array element to be ordered properly. for example if you have in an array [ 1, 3, 4, 'a', 'c', 'a'], sorting this will result to [ 1 , 3 , 4, 'a', 'a' , 'c' ], the next thing is to filter the returned array.

const unique = a => {
    if ( ! Array.isArray(a) )
        throw new Error(`${a} is not an array`);
    let val = a.sort().filter( (value, idx, array) => 
                 array[++idx] != value
             )
    return val;
}

let array = [ 1 , 5, 3, 2, "d", "q", "b" , "d" ];

unique(array); // [1, 2, 3, 5, "b", "d", "q"]

let obj = { foo: "bar" };

let arraySize = array.length;
array[arraySize] = obj;
array[arraySize++] = "foo";
array[arraySize++] = "baz";
array[arraySize++] = obj;

unique(array); // [1, 2, 3, 5, {…}, "b", "baz", "d", "foo", "hi", "q"]

it also works for all types, but if you pass in an array literal with arrays or objects as one of its element this code will fail

 unique( [ "a", 1 , 3 , "a", 3 , 3, { foo: "baz" }, { foo: "baz" } ] ); // it will not remove the duplicate of { foo: "baz" } , because they both have a different memory address

and you should also note that this code does not return the array in the same order it was passed in , this is as a result of the sort array method

0.sh
  • 2,659
  • 16
  • 37
0

Try using sets without generics. You can write a function as

Set returnUnique(Object array[]) {
Set set=new HashSet();
  for (Object obj:array) {
     set.add(obj);
}
return set;
}
codeLover
  • 2,571
  • 1
  • 11
  • 27