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
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 theindexOf
method will always return 0 for them.So to remove duplicated items, you can try this in
filter
:You filter removes the first occurrence of each value. Since
1
appears three times, you end up with two1
s.If you want only the first occurrence (remove duplicates), turn the
!==
into===
Maybe like this: