DEV Community

Discussion on: JS Program to Remove Duplicates From Array

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

Both of these solutions are exponentially slow due to the need to search the growing unique array (includes and indexOf do a linear search). You can do the unique array in O(N) using a Set, Map or in this case a PoJo. The one liner using Set is:

    const uniqueArr = [...new Set(array)]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hannaha88 profile image
hannaA

Best friends are options kk thanks

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

To add context here for learning purposes, a POJO is an object that only contains data (as opposed to methods or internal state), most JavaScript codebases consider objects created using curly braces {} to be POJOs, however, more strict codebases sometimes create POJOs by calling Object.create(null) to avoid inheriting from the built-in Object class.

JavaScript Maps are an alternative to POJOs for storing data because they neither inherit keys from the Object class.

A downside is that objects are generally easier to work with than maps cause not all JS functions, frameworks, and libs support maps.
i.e. JSON.stringify() function doesn't serialize maps by default:

const map = new Map([['score', 256, 'stage', 3]]);
JSON.stringify(map); // '{}'
Enter fullscreen mode Exit fullscreen mode