daiwik
1
function whatIsInAName(collection, source) {
var arr = [];
// Only change code below this line
for(let j = 0;j < collection.length;j++){
let obj = collection[j];
let objProps = Object.keys(obj);
let sourceProps = Object.keys(source);
let matchCounter = 0;
for(const prop in source){
if (obj.hasOwnProperty(prop)) {
if (obj[prop] === source[prop]) {
matchCounter++;
}
}
}
console.log(matchCounter);
for(const prop in source){
if (obj.hasOwnProperty(prop)) {
if ((obj[prop] === source[prop]) && matchCounter === sourceProps.length) {
arr.push(obj);
}
}
}
}
// Only change code above this line
return arr;
}
console.log(whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }));
Here is my solution so far. I get duplicates as return value. How do I fix it. Someone please help.
@daiwik Try Set method it will be perfect for your case. Set - JavaScript | MDN
Here is my solution to your problem.
Hope this was helpful. 
Happy Coding.
daiwik
3
sorry but it doesn’t work in https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou
arr can’t be changed.
I tried
creating let result = new Set(); and replaced arr with result. later assigned result to arr but no luck.
function whatIsInAName(collection, source) {
var arr = [];
// Only change code below this line
let result = new Set();
for(let j = 0;j < collection.length;j++){
let obj = collection[j];
let objProps = Object.keys(obj);
let sourceProps = Object.keys(source);
let matchCounter = 0;
for(const prop in source){
if (obj.hasOwnProperty(prop)) {
if (obj[prop] === source[prop]) {
matchCounter++;
}
}
}
for(const prop in source){
if (obj.hasOwnProperty(prop)) {
if ((obj[prop] === source[prop]) && matchCounter === sourceProps.length) {
result.add(obj);
}
}
}
}
arr = result;
// Only change code above this line
return arr;
}
console.log(whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }));
Instead do this
return [...new Set(arr)]