-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithm4.html
36 lines (27 loc) · 1.3 KB
/
algorithm4.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
<html>
<body>
<script>
//https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou
//Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument). Each name and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.
// matchObject({ first: "Romeo", last: "Montague" }, {last: "Montague"}) === true
function matchObject(object, source) {
var arr = Object.keys(source);
for (var i=0; i<arr.length; i++) {
var key = arr[i];
if (object[key] !== source[key]) {
return false;
}
}
return true;
}
function whatIsInAName(collection, source) {
return collection.filter(object => matchObject(object,source));
}
//tests
console.log(whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }));
console.log(whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 }));
console.log(whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}));
</script>
</body>
</html>