-1
How can i check if an array has element twice and log only the element that is not.
const duplicateElements = (array) => {

for(let numbers of array) {

 // code here

}
 
}

const numbers = [1,3,2,4,1,3,2];

duplicateElements(numbers);

// Output 4
  • 3
    What have you tried so far? There are a nuber of approaches that could be taken. – Dave Newton Feb 21 '22 at 19:47
  • 1
    Try searching stack overflow for this. There are probably a few dozen posts that will help – Kinglish Feb 21 '22 at 19:53
  • You could tally the elements, then select only the elements with a count of 1. Here is an example. https://gist.github.com/3limin4t0r/0c801e576a54855f20e84915f0440aba – 3limin4t0r Feb 21 '22 at 20:26

1 Answers1

0

With the JS function filter you can archive this. First you have to iterate your array. then check with the filter function how many times the current value is inside your array. If equal 1 then push to an result array.

const d = [];
const arr = [1,3,2,4,1,3,2]
arr.forEach((e) => { 
  if (arr.filter(x => x == e).length === 1) {    
    d.push(e);    
  }   
}) 

console.log(d);
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
  • A loop with *two* nested filters?! What's `c` for here; you don't use it. – Dave Newton Feb 22 '22 at 15:23
  • 1
    @DaveNewton You are right. I first wanted to save the result in a var. but then i used it immediately in the condition and forgot to delete the filter and the variable that was not needed. Thanks for the hint / review. Merci – Maik Lowrey Feb 22 '22 at 18:35