Javascript equivalent of array_unique in PHP

955 Views Asked by At

I've been looking for a native javascript function which represents the equivalent of PHP's

$Fruit_Bowl = array_unique($Fruit_Bowl);

I can recreate this myself, using a pair of nested loops:

  • the outer loop counts down through the array
  • the inner loop checks if the current element is a duplicate of something we've already had

Working Example:

let fruitBowl = [
  'apple',
  'apple',
  'apple',
  'apple',
  'apple',
  'banana',
  'banana',
  'cherry',
  'cherry',
  'cherry',
  'damson',
  'elderberry',
  'fig',
  'fig'
];

for (i = (fruitBowl.length - 1); (i + 1) > 0; i--) {
  for (j = (i + 1); j < fruitBowl.length; j++) {
    if (fruitBowl[j] === fruitBowl[i]) {
      fruitBowl.splice(i, 1);
    }
  }
}

console.log(fruitBowl);

But, surely there is something faster, more concise and more elegant than this?

(Perhaps in newer versions of javascript, if not in older ones?)

1

There are 1 best solutions below

4
On

[...] surely there is something faster, more concise and more elegant than this?

Yes, it turns out there is.

I'm less familiar with collections in Javascript like Map and Set but it turns out that Set very explicitly represents a special kind of Array which may only contain an element once.

Consequently, turning an array into a set and then back into an array:

fruitBowl = [... new Set(fruitBowl)];

is exactly what I needed.

Working Example:

let fruitBowl = [
  'apple',
  'apple',
  'apple',
  'apple',
  'apple',
  'banana',
  'banana',
  'cherry',
  'cherry',
  'cherry',
  'damson',
  'elderberry',
  'fig',
  'fig'
];

fruitBowl = [... new Set(fruitBowl)];

console.log(fruitBowl);