skip to Main Content

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];
const newArray = [...array];
let newArrFiltered = newArray.filter(
  (item, index) => array.indexOf(item) !== index
);
console.log(newArrFiltered); // [1, 1, 2, 5]

3

Answers


  1. Your answer is expected.

    The reason why only the first 1 is excepted and the others are left is because the indexOf method returns the first position of the searched item in the array. For example, array.indexOf(1) returns 0, which is the index of the first 1 in the array. If there are more 1s in the array, they will have different indexes, like 3 or 6, but the indexOf method will always return 0 for them.

    So to remove duplicated items, you can try this in filter:

    (item, index) => array.indexOf(item) === index
    
    Login or Signup to reply.
  2. You filter removes the first occurrence of each value. Since 1 appears three times, you end up with two 1s.

    If you want only the first occurrence (remove duplicates), turn the !== into ===

    Login or Signup to reply.
  3. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search