Skip to content

Instantly share code, notes, and snippets.

@joemaffei
Last active March 21, 2023 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemaffei/414fe8c6fdc0792e6d5df6582e667c09 to your computer and use it in GitHub Desktop.
Save joemaffei/414fe8c6fdc0792e6d5df6582e667c09 to your computer and use it in GitHub Desktop.
Array utility methods
// Methods I wish existed in the Array prototype
Array.prototype.filterEqual = function filterEqual(item) {
return this.filter(x => x === item);
}
Array.prototype.filterEqualBy = function filterEqualBy(key, item) {
return this.filter(x => x[key] === item);
}
Array.prototype.filterNotEqual = function filterNotEqual(item) {
return this.filter(x => x !== item);
}
Array.prototype.filterNotEqualBy = function filterNotEqualBy(key, item) {
return this.filter(x => x[key] !== item);
}
Array.prototype.filteredMap = function filteredMap(filterPredicate, mapPredicate) {
return this.reduce((result, current) => {
if (filterPredicate(current)) {
result.push(mapPredicate(current));
}
return result;
}, []);
}
Array.prototype.findEqual = function findEqual(item) {
return this.find(x => x === item);
}
Array.prototype.findEqualBy = function findEqualBy(key, item) {
return this.find(x => x[key] === item);
}
Array.prototype.findNotEqual = function findNotEqual(item) {
return this.find(x => x !== item);
}
Array.prototype.findNotEqualBy = function findNotEqualBy(key, item) {
return this.find(x => x[key] !== item);
}
Array.prototype.insert = function insert(index, item) {
this.splice(index, 0, item);
return this; // allow for chaining
}
/**
* Filters out null and undefined, then applies the map.
*/
Array.prototype.mapNonNullish = function mapNonNullish(predicate) {
return this.reduce((result, current) => {
if (current !== undefined && current !== null) result.push(predicate(current));
return result;
}, []);
}
/**
* Applies the map, then filters out null and undefined.
* Thank you @Reed-Anderson for the suggestion!
*/
Array.prototype.nonNullishMap = function nonNullishMap(predicate) {
return this.reduce((result, current) => {
const newVal = predicate(current);
if (newVal !== undefined && newVal !== null) {
result.push(newVal);
}
return result;
}, []);
}
Array.prototype.replace = function replace(findPredicate, replacePredicate) {
return this.map(x => findPredicate(x) ? replacePredicate(x) : x);
}
Array.prototype.replaceAt = function replaceAt(index, item) {
this[index] = item;
return this; // allow for chaining
}
Array.prototype.replaceBy = function replaceBy(key, finder, replacer) {
return this.map(x => x[key] === finder ? replacer : x);
}
Array.prototype.replaceWith = function replaceWith(finder, replacer) {
return this.map(x => x === finder ? replacer : x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment