Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active August 15, 2020 19:24
Show Gist options
  • Save dfkaye/d4bb3b2095ed08f8572c3df2d0067172 to your computer and use it in GitHub Desktop.
Save dfkaye/d4bb3b2095ed08f8572c3df2d0067172 to your computer and use it in GitHub Desktop.
omit.js removes array items that match every key-value in a descriptor
// 12 July 2020
// prompted by Cory House tweet
// @see https://twitter.com/housecor/status/1282375519481323520
function omit(array, descriptor) {
// Return the input if it's not an array, or if the descriptor is not an Object.
if (!Array.isArray(array) || descriptor !== Object(descriptor)) {
return array;
}
var keys = Object.keys(descriptor);
// Filter item where every descriptor key-value matches the item key-value.
return array.filter(function where(value) {
// Object(value) cast prevents 'in' operator access errors on primitive values.
var item = Object(value);
return ! keys.every(function matches(key) {
return key in item && item[key] === descriptor[key];
});
});
}
/* test it out */
// input not an array
console.log(omit("unchanged"));
// "unchanged"
// descriptor not an object
console.log(omit(["unchanged"], 1));
// ["unchanged"]
// remove self
var o = {id: 'remove', size: 1};
var arr = [o, { id: 'persist', size: 22 }, o];
var test = omit(arr, o);
console.log(JSON.stringify(test, null, 2));
/*
[
{
"id": "persist",
"size": 22
}
]
*/
// remove exact match on both name and value
var a = [
{name: "david"},
{name: "david", value: "remove"},
{name: "david", value: "remove", property: "a lot"},
{name: "david", value: "unchanged"}
];
var desc = {name: "david", value: "remove"};
var test = omit(a, desc);
console.log(JSON.stringify(test, null, 2));
/*
[
{
"name": "david"
},
{
"name": "david",
"value": "unchanged"
}
]
*/
// guard against primitives without keys
var p = [ 1, "two", null, undefined ];
var desc = {name: "david", value: "some"};
var test = omit(p, desc);
console.log(JSON.stringify(test, null, 2));
// JSON.stringify() converts undefined to null
/*
[
1,
"two",
null,
null
]
*/
// But last item should be undefined
console.log(test[4] === void 0);
// true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment