How to remove duplicates from an array and get only unique values in JavaScript?
Hello everyone! I'm new to JavaScript and encountered a problem when working with arrays.
I have an array containing duplicate values. I need to get a new array from it that contains only unique elements, that is, without duplicates. For example, I have this array:
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'kiwi', 'orange'];
I want to get as output: ['apple', 'banana', 'orange', 'kiwi'] — that is, each fruit appears only once, and the order is preserved based on the first occurrence.
I tried writing my own function with a loop and checking using indexOf, but the code turned out to be cumbersome and not very readable. I think in modern JavaScript there should be more elegant ways to do this. No answers yet.
Log in to leave an answer