0

For example, I have such array: var number2 = [1,3,4,1,5,6,3] and I want to output only repeated elements such as 1 and 3 without any method. My code is as follows:

for(let i=0; i<number2.length; i++){
    for(let j=0; j<number2.length; j++){
        if([i]!==[j] && number2[i]===number2[j]){
            console.log(number2[i]);
        }
    }
}

But it doesn't work how I want.

srvqaqa
  • 442
  • 1
  • 5
  • 18
  • this answer https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array and this one have many solutions to your problem https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates – Michael Aug 18 '19 at 18:29
  • 1
    use `i !== j` instead of `[i] !== [j]`. – Titus Aug 18 '19 at 18:30
  • Michael - it's the wrong one, the correct one is [Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array](https://stackoverflow.com/questions/840781/get-all-non-unique-values-i-e-duplicate-more-than-one-occurrence-in-an-array) linked there as similar. – Amadan Aug 18 '19 at 18:31
  • @Michael thank you, but none of answers can help me. I don't want to use any method. – srvqaqa Aug 18 '19 at 18:31
  • @srvqaqa That's impossible - `console.log` is a method (as is any other way that JavaScript has of outputting a value). – Amadan Aug 18 '19 at 18:32
  • @Amadan whoops sorry I misread the title, you're correct – Michael Aug 18 '19 at 18:32
  • @Amadan wow ! really ? I mean methods like sort, push, filter and etc. – srvqaqa Aug 18 '19 at 18:33
  • Everyone, he wants to output duplicates ... not remove duplicates :P – jriley88 Aug 18 '19 at 18:35

2 Answers2

0

[i] !== [j] Should be just i !== j.

number2[i] === number2[j] is correct.

jriley88
  • 117
  • 8
  • 1
    Something to be wary of, though OP did not clarify so maybe this is the desired behavior, is that this method will contain "duplcate duplicates". For example if the array is [1, 1] then the code would output 1 1. The situation is even worse with [1, 1, 1] which yields output "1 1 1 1 1 1". – Michael Aug 18 '19 at 18:37
  • You're correct because he's looping twice. Maybe that can be his next discovery :D – jriley88 Aug 18 '19 at 18:38
0

If you need less complexity [instead of O(n^2), O(n)] you can use a map over there. just loop over the array you have, and put each digit in map with its occurrences.

var map = new Map();
for(var i=0; i<arr.length; i++){
     var val = map.get(arr[i]);
     // if key found [such as, if the value already exist in array]
     if(!isNaN(val))
        map.set(arr[i], val+1);

    // if key not found[such as, if the value found for the first time in array]
    else
        map.set(arr[i], 1);
}
// iterate over the map, and print only those value whose occourance is >1. 
for(var [key, value] of map){
    if(value > 1)
      console.log(key);
}
Papai from BEKOAIL
  • 1,469
  • 1
  • 11
  • 17