'JavaScript filter method not giving unique result [closed]
i am trying to filter the unique ones from a given array using filter method but its throwing an empty array, here is the code
function dual(a) {
if (Array.isArray(a)) {
let unique = a.filter((val, index) => {
a.indexOf(val) == index
})
return unique;
}
}
console.log(dual([3, 1, 1, 2, 2])) //expected result [3,1,2] but showing []
Solution 1:[1]
You may use Set() to create a unique array:
const arr = [3,1,1,2,2]
var uniqueArray = [...new Set(arr)]
console.log(uniqueArray)
Solution 2:[2]
You are missing return statements from both your function and your filter array method.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R.dev |
| Solution 2 | Jack |
