0

I have an array with multiples of certain automobiles, included within it. I am trying to return an array with one of every item, without duplicates.

I have a functioning piece of code, using an if...else format, but cannot achieve the same result with a conditional statement, in JavaScript. It says that list.includes(automobile) is not a function.

const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck'];
let noDuplicates = data.reduce((list, automobile) => {
  if (list.includes(automobile)) {
    return list
  } else {
    return [...list, automobile]
  }
}, []);

console.log(noDuplicates)

This version with if...else, works, but where I'm struggling to achieve the same result is with a conditional statement, like the following:

const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck'];
let noDuplicates = data.reduce((list, automobile) => {
   list.includes[automobile] ? list : [...list, automobile]
}, []);

console.log(noDuplicates)

I assume I may have some parenthesis missing, or in the wrong place, but it appears correct to me. The if...else statement returned exactly what I was looking for, ["car", "truck", "bike", "walk", "van"], but the conditional statement was not.

Code Maniac
  • 37,143
  • 5
  • 39
  • 60

1 Answers1

4

Why my code is not working ?

  • Missing return statement
  • list.includes[automobile] this should be list.includes(automobile)

const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck'];
let noDuplicates = data.reduce((list, automobile) => {
   return list.includes(automobile) ? list : [...list, automobile]
}, []);

console.log(noDuplicates)

You can simply use Set

const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
let unique = [...new Set(data)]

console.log(unique)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Also Why `...` is getting ***unexpected token*** without `[]` ? – hs-dev2 MR Jul 25 '19 at 02:29
  • @hs-dev2MR `[...]` to get values from Set, you can read here [`Set MDN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set), `...` without `[]` is invalid syntax [`Destructuring`](https://stackoverflow.com/questions/54605286/what-is-destructuring-assignment-and-its-uses) – Code Maniac Jul 25 '19 at 02:33
  • Okay I got it ! I love u now – hs-dev2 MR Jul 25 '19 at 02:38