-1

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

temosmoev
  • 1
  • 2
  • So are you just trying to find if a function is listed twice? E.g. ```let arr = [func1, func1, func2]```? – Mrbisquit Mar 20 '23 at 19:59
  • Functions are not different than any other variables, this is a duplicate question. Please check if your question is already answered before posting. – snnsnn Mar 20 '23 at 20:28
  • @snnsnn It may be a duplicate or be closed as "Needs more details or clarity", but your linked question does not answer their question. It seems that they are trying to remove duplicates based on the return value or body of the functions... – kelsny Mar 20 '23 at 20:39
  • I've voted to close as unclear question. What are duplicate functions? Are `let a = 0; function f() { a = 1; return 1; } function g() { a = 2; return 1; }` duplicate functions? – Thomas Sablik Mar 20 '23 at 21:28

2 Answers2

2

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)
kelsny
  • 23,009
  • 3
  • 19
  • 48
Andrew
  • 630
  • 1
  • 5
  • 14
0

You could use lodash library (Docs here):

import _ from 'lodash';

const uniqueValues = _.uniq(arr)
Cruz
  • 85
  • 1
  • 1
  • 5
  • This does not answer the question as it uses [SameValueZero](https://262.ecma-international.org/7.0/#sec-samevaluezero) comparison. OP is asking to remove duplicates based on the returned value or body of the functions, not if the are the same reference. – kelsny Mar 20 '23 at 20:40
  • yeah, this will not work :( but thanks for the answer! – temosmoev Mar 20 '23 at 21:01