Returns a unique element that has no duplicates in the array

I am trying to return an array with only unique elements that do not have duplicates in the array without any special order.

[1,2,3,3,3,4,4,2] will return 1

["hello", "truck", 2, "truck", 2, "truck"] will return "hello"

So far, I have managed to return unique elements using the filter () function, but I'm not sure where to go.

Basically, if there are duplicates, I want both values ​​to be removed from the array.

It sounds simple enough, but I have a serious mental hiccup.

Below is my code:

 function diff(arr1, arr2) { var newArr = []; newArr = arr1.concat(arr2); newArr = newArr.filter(function(elem, index, self) { return index == self.indexOf(elem); }); console.log(newArr); return newArr; } diff([1, 2, 3, 5], [1, 2, 3, 4, 5]); //should return 4 
+5
source share
3 answers

Compare indexOf and lastIndexOf , if they are equal, then the element has no duplicates. Use .filter with this logic.

 function diff(arr1, arr2) { return arr1.concat(arr2).filter(function(elem, index, self) { return self.indexOf(elem)==self.lastIndexOf(elem); }); } alert(diff([1, 2, 3, 5], [1, 2, 3, 4, 5])); 
+6
source

You can do something like this:

 function findUniques(arr) { var i = 0; while(i !== arr.length) { if(arr.slice(i+1,arr.length-1).indexOf(arr[i]) > -1) { arr = arr.splice(i,0); } else { i++; } } } 

This will leave the unique elements in the array in the reverse order as they were found. To avoid this, you iterate from the end of the array and let me reduce it to zero if you need order.

+1
source

To get only unique elements in an array, you can use the filter method as follows:

 function unique(val, index, self) { return index === self.indexOf(val); } 

You can use it like this:

 var arr = ['1','2','3','3']; var uniqueArr = arr.filter(unique); // will return ['1', '2', '3'] 

This will work without jQuery or prototype.js and for arrays with mixed type values.

-1
source

Source: https://habr.com/ru/post/1239367/


All Articles