-2

I am using filter method of JavaScript to remove the duplicate entries and I am using the below syntax:

var dataArray = ['g','o','o','g','l','e']
dataArray.filter((value, index) => dataArray.indexOf(value) === index)

The above code works fine and returns me an array by removing the duplicate values. But, when I add a { curly braces after arrow function it returns an empty array.

var dataArray = ['g','o','o','g','l','e']
dataArray.filter((value, index) => { dataArray.indexOf(value) === index })

I am unable to figure out what's the actual difference between both of the syntaxes and why the second one is returning me an empty array.

HarshSharma
  • 630
  • 3
  • 9
  • 34
  • The first is an expression, the second a block. `{ }` are not only for cosmetics. – Andreas Feb 23 '21 at 13:25
  • 1
    you need a return statement with curly brackets. – Nina Scholz Feb 23 '21 at 13:26
  • try to log the result of calling `dataArray.filter(...)` to know the difference. 2nd code example will not work like you expect it to. – Yousaf Feb 23 '21 at 13:26
  • You can try reading up the comparison in the mdn documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#comparing_traditional_functions_to_arrow_functions – ryeballar Feb 23 '21 at 13:27

1 Answers1

0

You have to specify the return keyword if use curly brace:

var dataArray = ['g','o','o','g','l','e']
dataArray = dataArray.filter((value, index) => { return dataArray.indexOf(value) === index });

console.log(dataArray);

Though, I prefer using Set to remove duplicate items from array:

var dataArray = ['g','o','o','g','l','e']
dataArray = [...new Set(dataArray)];

console.log(dataArray);
Mamun
  • 66,969
  • 9
  • 47
  • 59