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.

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Also Why ... is getting unexpected token without [] ?
@hs-dev2MR [...] to get values from Set, you can read here Set MDN, ... without [] is invalid syntax Destructuring
Okay I got it ! I love u now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.