Samir Parikh / Blog


Originally published on 07 October 2019

The following program takes an unsorted array containing duplicate entries and finds the unique values and sorts them into a new array:

import std.stdio: writeln;
import std.conv;
import std.algorithm;
import std.array;

void main() {
    int[] unsortedArray = [5, 3, 8, 5, 2, 3, 0, 8];
    int[] uniqueArray;

    uniqueArray = uniq(sort(unsortedArray)).array;
    // or you can use
    // uniqueArray = unsortedArray.sort().uniq.array;

    writeln(uniqueArray); // [0, 2, 3, 5, 8]
}

Note that the .array is required because we are storing the results in a new array.