@churchapps/apphelper
Version:
Library of helper functions for React and NextJS ChurchApps
89 lines • 3.05 kB
JavaScript
import { UniqueIdHelper } from "./UniqueIdHelper";
export class ArrayHelper {
static getIds(array, propertyName) {
const result = [];
for (const item of array) {
const id = item[propertyName]?.toString();
if (!UniqueIdHelper.isMissing(id) && result.indexOf(id) === -1)
result.push(id);
}
return result;
}
static sortBy(array, propertyName, descending = false) {
array.sort((a, b) => {
const valA = a[propertyName];
const valB = b[propertyName];
if (valA < valB)
return descending ? 1 : -1;
else
return descending ? -1 : 1;
});
}
static getIndex(array, propertyName, value) {
for (let i = 0; i < array.length; i++) {
const item = array[i];
if (ArrayHelper.compare(item, propertyName, value))
return i;
}
return -1;
}
static getOne(array, propertyName, value) {
for (const item of array || [])
if (ArrayHelper.compare(item, propertyName, value))
return item;
return null;
}
static getAll(array, propertyName, value) {
const result = [];
for (const item of array || []) {
if (ArrayHelper.compare(item, propertyName, value))
result.push(item);
}
return result;
}
static getAllArray(array, propertyName, values) {
const result = [];
for (const item of array || [])
if (values.indexOf(item[propertyName]) > -1)
result.push(item);
return result;
}
static getAllContaining(array, propertyName, value) {
const result = [];
for (const item of array)
if (item[propertyName].toString().toLowerCase().indexOf(value.toLowerCase()) > -1)
result.push(item);
return result;
}
static compare(item, propertyName, value) {
const propChain = propertyName.split(".");
if (propChain.length === 1)
return item[propertyName] === value;
else {
let obj = item;
for (let i = 0; i < propChain.length - 1; i++) {
if (obj)
obj = obj[propChain[i]];
}
return obj[propChain[propChain.length - 1]] === value;
}
}
static getUniqueValues(array, propertyName) {
const result = [];
for (const item of array) {
const val = (propertyName.indexOf(".") === -1) ? item[propertyName] : this.getDeepValue(item, propertyName);
if (result.indexOf(val) === -1)
result.push(val);
}
return result;
}
static getDeepValue(item, propertyName) {
const propertyNames = propertyName.split(".");
let result = item;
propertyNames.forEach(name => {
result = result[name];
});
return result;
}
}
//# sourceMappingURL=ArrayHelper.js.map