diff --git a/README.md b/README.md index c237bde..7ada02a 100644 --- a/README.md +++ b/README.md @@ -390,6 +390,17 @@ let deepFlattenedArray3 = helpful.deepFlattenArray([[0, 1], [2, [3, 4, [5, [6]]] **Return Type:** Array (`Array(5) [0, 1, 2, 3, 4]`) +### differenceOfObjects +Finds the difference of two objects (any keys that are present in the second object are removed from the first) +```javascript +let differenceOfObjs = helpful.differenceOfObjects({"a": 1, "b": 2}, {"b": 3, "c": 4}); // {"a": 1} +``` +**Parameters:** +- object1: Object (`{"a": 1, "b": 2}`) +- object2: Object (`{"b": 3, "c": 4}`) + +**Return Type:** Object (`{"a": 1}`) + ## Hex ### hex.convertFromString diff --git a/helpful.js b/helpful.js index b17a45a..e47c648 100644 --- a/helpful.js +++ b/helpful.js @@ -235,6 +235,22 @@ return res; } + helpful.differenceOfObjects = function(object1, object2){ + if(Object.keys(object1).length === 0 || Object.keys(object2).length === 0) { + return []; + } + let array1 = Object.keys(object1); + let array2 = Object.keys(object2); + for(let i = 0; i < array1.length; i++){ + for(let j = 0; j < array2.length; j++){ + if(array1[i] == array2[j]){ + delete object1[array1[i]]; + } + } + } + return object1; + } + helpful.hex = {}; /* Modified from https://github.com/TogaTech/tEnvoy */ diff --git a/test/tester.js b/test/tester.js index 3bf5781..e906fc6 100644 --- a/test/tester.js +++ b/test/tester.js @@ -211,6 +211,13 @@ describe("Tests", function() { let actual = helpful.deepFlattenArray([[0, 1], [2, [3, 4, [5, [6]]]]]); assert.deepEqual(expected, actual); }); + + i++; + it(`${i}: differenceOfObjects - Should remove any keys from the first object that are presented in the second object`, function() { + let expected = {"a": 1}; + let actual = helpful.differenceOfObjects({"a": 1, "b": 2}, {"b": 3, "c": 4}); + assert.deepEqual(expected, actual); + }); }); describe("Hex", function() {