I am new to JavaScript and am trying to create a function that would take an array, and return a new array containing true for duplicate elements in the original array, and false otherwise. Here is the code I wrote:
count = function(arr, item) {
let number = 0
arr.forEach(elem => {
if (elem == item) {
number++
}
})
return number
}
findAllOccurrences = function(arr, target) {
const duplicatesList = arr.filter(elem => {
if (count(arr, elem) > 1) {
return true
} else {
return false
}
})
return duplicatesList
}
console.log(findAllOccurrences([1, 2, 2, 3, 4, 2, 5, 4], 2))
But it gives me duplicate values instead of true/false.
[false, true, true, false, true, false, false, true]
[ 2, 2, 4, 2, 4 ]
What I want to ask is, how does arr.filter function work?