Monday, 6 November 2023

JS - array unqiue

checking an item exists in array then push is costly o(n)


cleaning up array in the end is o(n) but more effecient:

https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates


https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array


"Smart" but naïve way

uniqueArray = a.filter(function(item, pos) {
    return a.indexOf(item) == pos;
})

Basically, we iterate over the array and, for each element, check if the first position of this element in the array is equal to the current position

No comments:

Post a Comment