diginext-utils
Version:
README.md
39 lines • 1.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.unique = unique;
/**
* Creates an array of unique values from one or more arrays.
* If a key is provided, uniqueness is determined by that property.
*
* @template T - The type of elements in the arrays
* @param arrays - One or more arrays to combine and make unique
* @param key - Optional key to determine uniqueness for objects
* @returns A new array with unique values
*
* @example
* ```ts
* unique([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4]
* unique([1, 2], [2, 3], [3, 4]); // [1, 2, 3, 4]
* unique([{ id: 1 }, { id: 1 }, { id: 2 }], 'id'); // [{ id: 1 }, { id: 2 }]
* ```
*/
function unique(arrays, key) {
// Flatten if multiple arrays provided
const flatArray = Array.isArray(arrays[0]) && arrays.length > 1 ? arrays.flat() : arrays;
if (!Array.isArray(flatArray) || flatArray.length === 0) {
return [];
}
if (key !== undefined) {
const seen = new Set();
return flatArray.filter((item) => {
const value = item[key];
if (seen.has(value)) {
return false;
}
seen.add(value);
return true;
});
}
return Array.from(new Set(flatArray));
}
//# sourceMappingURL=unique.js.map