I have an array a = [1, 2, 3, 4, 5, 1, 2, 3]
How do I get an array b = [4, 5]
. How to remove all elements that have duplicates?
I have an array a = [1, 2, 3, 4, 5, 1, 2, 3]
How do I get an array b = [4, 5]
. How to remove all elements that have duplicates?
Need to loop over it and see if it exists. Easiest way is to sort and look at its neighbors.
var nums = [1, 2, 3, 4, 5, 1, 2, 3];
var noDupes = nums.slice().sort() //sort it so numbers line up
.reduce(function(result, c, i, arr){ //loop over the set
if (c !== arr[i+1] && c !== arr[i-1]) { //see if number is before or after
result.push(c) //if not, than add it
}
return result
}, [])
console.log(noDupes);
var noDupes2 = nums.slice().sort()
.filter((c, i, arr) => c !== arr[i+1] && c !== arr[i-1])
console.log(noDupes2);
Another solution is to look at indexes without sorting
var nums = [1, 2, 3, 4, 5, 1, 2, 3];
var noDupes = nums.filter(( c, i, arr) => arr.indexOf(c) === arr.lastIndexOf(c))
console.log(noDupes)
By filtering the ones that the index isn't the same as the last index;
a = [1, 2, 3, 4, 5, 1, 2, 3];
//console.log(a);
b = a.filter((value) => a.indexOf(value) == a.lastIndexOf(value));
console.log(b)