locutus
Version:
Locutus other languages' standard libraries to JavaScript for fun and educational purposes
41 lines (40 loc) • 1.71 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.array_unique = array_unique;
const _phpTypes_ts_1 = require("../_helpers/_phpTypes.js");
function array_unique(inputArr) {
// discuss at: https://locutus.io/php/array_unique/
// original by: Carlos R. L. Rodrigues (https://www.jsfromhell.com)
// input by: duncan
// input by: Brett Zamir (https://brett-zamir.me)
// bugfixed by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Nate
// bugfixed by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Brett Zamir (https://brett-zamir.me)
// improved by: Michael Grier
// note 1: The second argument, sort_flags is not implemented;
// note 1: also should be sorted (asort?) first according to docs
// example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin'])
// returns 1: {0: 'Kevin', 2: 'van', 3: 'Zonneveld'}
// example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'})
// returns 2: {a: 'green', 0: 'red', 1: 'blue'}
const tmpArr2 = {};
const inputObj = (0, _phpTypes_ts_1.toPhpArrayObject)(inputArr);
const _arraySearch = function (needle, haystack) {
let fkey = '';
for (fkey in haystack) {
if (Object.hasOwn(haystack, fkey)) {
if (String(haystack[fkey]) === String(needle)) {
return fkey;
}
}
}
return false;
};
for (const [key, val] of (0, _phpTypes_ts_1.entriesOfPhpAssoc)(inputObj)) {
if (_arraySearch(val, tmpArr2) === false) {
tmpArr2[key] = val;
}
}
return tmpArr2;
}