-1

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?

N. Levenets
  • 77
  • 1
  • 1
  • 8

2 Answers2

0

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)
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

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)
Steve0
  • 2,233
  • 2
  • 13
  • 22
  • That's the same as the accepted answer at the duplicate. – RobG Oct 18 '18 at 20:30
  • That's true, I must have been in snippet editing mode when this question got marked as dupe. The quick dupe searching I did revealed leaving one occurence there, similar to `SQL DISTINCT`. Should I remove the answer or leave it here? – Steve0 Oct 18 '18 at 20:34