skip to Main Content

I have 3 functions

const func1 = () => {
  return 1
}
const func2 = () => {
  return 1
}
const func3 = () => {
  return 2
}
let arr = [func1, func2, func3]

how can I filter dublicates (func1 and func2) from arr, so that I will have something like this filteredArr=[()=>{return 1},()=>{return 2}] ?

tried to stringify each of them and then use if with eval but I want to filter the array without using eval

2

Answers


  1. You can filter the array with an additional check inside, but this requires you to call the functions.

    const func1 = () => {
      return 1
    }
    const func2 = () => {
      return 1
    }
    const func3 = () => {
      return 2
    }
    
    let arr = [func1, func2, func3]
    
    const uniqueItems = arr.filter((func, index, array) =>
      index === array.findIndex(f => f() === func())
    )
    
    console.log(uniqueItems)
    Login or Signup to reply.
  2. You could use lodash library (Docs here):

    import _ from 'lodash';
    
    const uniqueValues = _.uniq(arr)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search