Reputation: 1
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.
Upvotes: 0
Views: 167
Reputation: 37755
Why my code is not working ?
return
statementlist.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)
Upvotes: 4