src/utilities/ArrayUtility.js
/**
* http://stackoverflow.com/a/13319168
* arr1 and arr2 are arrays of any length; eqFn is a function which
* can compare two items and return true if they're equal and false otherwise
* @param {Array} arr1 - Array of any length
* @param {Array} arr2 - Array of any length
* @param {Function<Boolean>} eqFn - Function which returns a Boolean
*/
function union(arr1, arr2, eqFn) {
return unique(arr1.concat(arr2), eqFn);
}
/**
* Returns an array with unique values given the Eq Function
* @param {Array} arr - Array that may contain duplicates
* @param {Function<Boolean>} eqFn - A function that returns a Boolean
*/
function unique(arr, eqFn) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (eqFn(arr[i], arr[j])) {
arr.splice(j, 1);
j--;
}
}
}
return arr;
}
/**
* Convert the Array to an object
*
* @param {Array} _array - The array to convert to an object
* @param {Object} [options] - Options on how to conver the array
* @return {Object} - The resulting object from the array
*/
function arrayToObject(_array, options = undefined) {
const _obj = {};
let i = 0;
_array.forEach((obj) => {
const key = (options && options.key) ? obj[options.key] : obj.id || ++i;
if (key !== undefined && key !== null) {
_obj[key] = obj;
}
});
return _obj;
}
export { union, unique, arrayToObject };