1

I need to return duplicates in a new array and get this output: [1, 2, 5] but get two times 1. why?

const array = [1, 2, 3, 1, 5, 6, 1, 2, 5];
let newArrFiltered = array.filter(
  (item, index) => array.indexOf(item) !== index
);
console.log(newArrFiltered); // [1, 1, 2, 5]
Xena
  • 379
  • 3
  • 9
  • 4
    Please don't post images of code. Type the code. – trincot Jul 22 '23 at 13:26
  • 1
    Note that`filter` returns a new array. In this instance making a copy of the array is unnecessary. – Andy Jul 22 '23 at 13:28
  • 1
    Have you debugged this? There are exactly two `1` in your input array for which `array.indexOf(item) !== index` is true. Why does this surprise you? Just check what the value is of `array.indexOf(1)` and then check what `index` is for each occurrence of 1... – trincot Jul 22 '23 at 13:28
  • 1
    For how to use `indexOf` for this purpose, see [here](https://stackoverflow.com/a/8315486/5459839). – trincot Jul 22 '23 at 13:36

1 Answers1

0

Maybe like this:

var array = [1,2,3,1,5,6,1,2,5];
var test_arr = [];
var exist_arr = [];
for(var key in array){ 
   if(test_arr.indexOf(array[key]) === -1){
        test_arr.push(array[key]);
   }else{
       if(exist_arr.indexOf(array[key]) === -1){
           exist_arr.push(array[key]);
       }
   }

}

console.log(exist_arr);
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17